Interfaces
One of TypeScript’s core principles is that type checking focuses on the shape that values have. This is sometimes called "duck typing" or "structural subtyping".
Our First Interface
The printLabel function has a single parameter that requires that the object passed in has a property called label
of type string. If the object passed in has more properties than this, the compiler will ignore it.
The interface LabeledValue
is a name we can now use to describe the requirement in the previous example.
Optional Properties
Interfaces with optional properties are written similar to other interfaces, with each optional property denoted by a ? at the end of the property name in the declaration.
The advantage of optional properties is that you can describe these possibly available properties while still also preventing use of properties that are not part of the interface.
Readonly properties
Variables use const
whereas properties use readonly
.
Excess Property Checks
Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments.
If an object literal has any properties that the “target type” doesn’t have, you’ll get an error.
We could solve this by adding a string index signature if you’re sure that the object can have some extra properties that are used in some special way.
Function Types
To describe a function type with an interface, we give the interface a call signature.
Indexable Types
Indexable types have an index signature that describes the types we can use to index into the object.
There are two types of supported index signatures: string
and number
. It is possible to support both types of indexers, but the type returned from a numeric indexer must be a subtype of the type returned from the string indexer.
While string index signatures are a powerful way to describe the "dictionary" pattern, they also enforce that all properties match their return type.
You can make index signatures readonly in order to prevent assignment to their indices.
Class Types
Implementing an interface
The static and instance sides
To work with the static side of the class directly, we should define two interfaces.
Extending Interfaces
Like classes, interfaces can extend each other. An interface can extend multiple interfaces, creating a combination of all of the interfaces.
Hybrid Types
An object could act as both a function and an object, with additional properties.
Last updated