A TypeScript interface describes a JavaScript object. Such an object is analogous to a Python dictionary with well-known string keys, which is described by a TypedDict.
TypeScript interface example
For example the TypeScript interface:
interface Address {
street: string;
housenumber: number;
}
will describe JavaScript objects like:
var someAddress = {
street: 'SW Gemini Dr.',
housenumber: 9450,
};
Python TypedDict example
The equivalent Python TypedDict
:
from typing import TypedDict
class Address(TypedDict):
street: str
housenumber: int
will describe Python dictionaries like:
some_address = {
'street': 'SW Gemini Dr.',
'housenumber': 9450,
}
# or equivalently:
some_address = dict(
street='SW Gemini Dr.',
housenumber=9450,
)
These dictionaries can be serialized to/from JSON trivially and will conform to the analogous TypeScript interface type.
Note: If you are using Python 2 or older versions of Python 3, you may need to use the older function-based syntax for TypedDict:
from mypy_extensions import TypedDict
Address = TypedDict('Address', {
'street': str,
'housenumber': int,
})
Alternatives
There are other ways in Python to represent structures with named properties.
Data classes, available in Python 3.7, have read-write keys. However they cannot be serialized to/from JSON automatically.
from dataclasses import dataclass
@dataclass
class Address:
street: str
housenumber: int
my_address = Address(
street='SW Gemini Dr.',
housenumber=9450,
)
Named tuples are cheap and have read-only keys. They also cannot be serialized to/from JSON automatically.
from typing import NamedTuple
class Address(NamedTuple):
street: str
housenumber: int
my_address = Address(
street='SW Gemini Dr.',
housenumber=9450,
)
Simple namespaces, available in Python 3.3, are similar to data classes but are not very well known.
from types import SimpleNamespace
class Address(SimpleNamespace):
street: str
housenumber: int
my_address = Address(
street='SW Gemini Dr.',
housenumber=9450,
)
attrs is a long-standing third-party library that is similar to data classes but with many more features. attrs is recognized by the mypy typechecker.
import attrs
@attr.s(auto_attribs=True)
class Address:
street: str
housenumber: int
my_address = Address(
street='SW Gemini Dr.',
housenumber=9450,
)