- Mastering TypeScript 3
- Nathan Rozentals
- 246字
- 2021-07-02 12:42:50
Weak types
When an interface contains only optional properties, it is considered a weak type. In other words, if we create an object that implements a weak type interface, can we really say that the object implements the interface? Let's consider some code to find out, as follows:
interface IWeakType { id?: number, name?: string } let weakTypeNoOverlap: IWeakType; weakTypeNoOverlap = { description: "my description" };
Here, we have defined an interface named IWeakType that contains two properties, named id and name. As both of these properties are optional, this interface is considered to be a weak type. We then define a variable named weakTypeNoOverlap, and specify this object to be of type IWeakType. On the last line of this code, we assign a value to this variable that has a description property. Note that there is no overlap between the properties we have assigned to the variable and the interface that it is supposed to be implementing.
In this case, the TypeScript compiler will generate the following error:
error TS2322: Type '{ description: string; }' is not assignable to type 'IWeakType'. Object literal may only specify known properties, and 'description' does not exist in type 'IWeakType'.
Here, we can see that the compiler is detecting that the weakTypeNoOverlap variable must implement the IWeakType interface, or at least some part of it. As there is no overlap between the properties of the IWeakType interface and the variable assignment, the assignment will generate an error.