What are interface and type?
Interface is the type of an interface
- Can be extended (“Extends and implements”)
- Properties merging (“Declaration merging”)
Type is a type alias
- Basic types can be aliased
Both type and interface work
When they describe an Object, they are very similar
// interface
interface IPerson {
firstName: string
lastName: string
}
interface Iadd {
(x:number.y:number) :number
}
// type
type Person = {
firstName: string
lastName: string
}
type Add = {
(x:number.y:number) :number
};
Copy the code
Type works and interface doesn’t
Primitive type aliases, union types, tuples, and so on
// Base type alias
type id = number
// Union type
type Names = "zhangsan" | "lisi";
// Specify the type of each position in the array
type List = ["abc".number]
Copy the code
Use Typeof to get the instance type for assignment
// Typeof performs the assignment
const initialState = {
todos: [] as Todo[],
};
type TodoState = typeof initialState;
Copy the code
Interface works and type doesn’t
A statement to merge
// declare the merged IPerson to contain firstName, lastName, nickName attributes
interface IPerson {
firstName: string
lastName: string
}
interface IPerson {
nickName: string
}
Copy the code
How to use better?
use whatever suites you and your team, just be consistent
Interface and type can be used, but it is important to keep the whole team consistent