1. Object types — Interfaces
In TypeScript, we use Interfaces to define the types of objects.
What is an interface a very flexible concept, it is an abstraction of behavior, in addition to the class can be used to abstract part of the behavior, but also commonly used to describe the “Shape of an object”.
As shown in the figure above, we use interfaces to define a “People” object, specify the type of its internal attributes, and define a variable Tom whose type is “People”. Then Tom’s internal attributes and the type of the attributes must be the same as “People”. Otherwise an error will be reported:
Similarly, when we define attributes in Tom that do not match the interface, an error will be reported, visibleWhen assigning, the shape of the variable must match the shape of the interface.
2. So how how is the attribute optional?
All we have to do is, when we define the interface, we put an optional attribute, right? You can implement the optional properties:
We defined sex as an optional property when we defined the interface. We did not define sex when we defined the variable James, but no error was reported.
3. Arbitrary attributes
Sometimes we want an interface to allow arbitrary properties. We can do this:
Use [people: string] to define any attribute to take a value of type string.
Note: Once an arbitrary attribute is defined, the type of both the deterministic attribute and the optional attribute must be a subset of its type
That is, the type of the NUM attribute must be a subset of the custom attribute type
4. Read-only property
Sometimes we want some fields in an object to be assigned only at creation time, so we can define the read-only property with readonly
interface Person { readonly id: number; name: string; age? : number; [propName: string]: any; } let tom: Person = { id: 89757, name: 'Tom', gender: 'male' }; tom.id = 9527; // index.ts(14,5): error TS2540: Cannot assign to 'id' because it is a constant or a read-only property.Copy the code
In the example above, the attribute ID defined with readonly was initialized and then assigned, so an error was reported.
Note: the read-only constraint exists on the first assignment to an object, not on the first assignment to a read-only attribute.
The second is an error when assigning tom.id because it is read-only.