This is the 13th day of my participation in the August More Text Challenge. For details, see:August is more challenging
The interface definition
One of the core features of TypeScript is type-checking of the structure of data. In addition to basic type annotations, you can also use interfaces to annotate data of object types.
Interface: a way to annotate complex object types or to define a contract (such as a class) for other code
interface Point {
x: number;
y: number;
}
Copy the code
The above code defines a type that contains two properties, an X of type number and a y of type Number. Multiple properties in the interface can be separated by commas or semicolons
We can use this interface to type a data
let p1: Point = {
x: 100,
y: 100
};
Copy the code
Note: An interface is a type and cannot be used as a value
interface Point { x: number; y: number; } let p1 = Point; // This is wrongCopy the code
Of course, the rules defined by interfaces are much more than that,
Optional attribute
The interface can also define optional properties by? To annotate
interface Point { x:number; y:number; color? : string; }Copy the code
Which color? Indicates that this property is optional
Read-only property
We can also make the property read-only using readonly
interface Point{
readonly x: number;
readonly y: number;
}
Copy the code
When a property is labeled read-only, it cannot be assigned to anything other than the initial value
Any attribute
Sometimes, if you want to add arbitrary attributes to an interface, you can do so using the index type
Numeric type index
interface Point {
x: number;
y: number;
[prop: number]: number;
}
Copy the code
String index
interface Point {
x: number;
y: number;
[prop: string]: number;
}
Copy the code
Numeric indexes are subtypes of string indexes
Note: The index signature parameter type must be either string or number, but both can occur at the same time
interface Point{
[prop:string]: string;
[prop1:number]: string;
}
Copy the code
Note: When both numeric and string indexes exist, the numeric value type must be a string value type or subtype
interface Point1 { [prop1: string]: string; [prop2: number]: number; } interface Point2 {[prop1: string]: Object; [prop2: number]: Date; / / correct}Copy the code
Use interface description functions
We can also use an interface to describe a function
interface IFunc {
(a: string): string;
}
let fn: IFunc = function(a) {}
Copy the code
Note that if you use an interface to describe a function by itself, there is no key
Interface with
Multiple interfaces with the same name are merged into one interface
interface Box {
height: number;
width: number;
}
interface Box {
scale: number;
}
let box: Box = {
height: 5,
width: 6,
scale: 10
}
Copy the code
- If the merged interface has non-function members with the same name, they must be of the same type or the compiler will report an error
- Functions of the same name in the interface are overloaded