Interface is to JavaScript The randomness of itself , By defining an interface , Agreed variables 、 class 、 In what format should functions be declared , Realize the consistency of multi person cooperation .TypeScript The compiler relies on interfaces for type checking , The final compilation is JavaScript after , The interface will be removed .
Optional attribute
The meaning of an optional attribute is that the attribute may not exist when it is defined by a variable .
interface Clothes {
color: string;
size: string;
price?: number;
}
// You can not define attributes here price
let myClothes: Clothes = {
color: 'blue',
size: 'XL'
}
Interfaces with optional properties are similar to normal interface definitions , Just add a... After the optional attribute name definition ?
Symbol .
remarks : Common clothing models are :S( Small )、M( in )、L( Big )、XL( enlarge );
Read-only property
Some object properties can only change their values when the object is just created . You can use... Before the attribute name readonly To specify read-only properties , such as , Once the clothes are made , Then the color and size cannot be modified :
interface Clothes {
readonly color: string;
readonly size: string;
price?: number;
}
let myClothes: Clothes = {
color: 'BLUE',
size: 'XL',
price: 99
}
// Do not modify the
myClothes.color= 'BLACK'
// error TS2540: Cannot assign to 'color' because it is a constant or a read-only property
Any attribute
Sometimes we want interfaces to allow arbitrary attributes , It can be used []
Wrap attributes :
interface Clothes {
readonly color: string;
readonly size: string;
price?: number;
[prop: string]: any;
}
// Any attribute activity
let myClothes: Clothes = {
color: 'BLUE',
size: 'XL',
price: 99,
factory: 'china'
}
Code instructions : Interface Clothes You can have any number of attributes , As long as they are not color size and price that will do , So it doesn't matter what type they are .
Link to the original text :http://www.mybatis.cn/typescript/1978.html