created at 2023/08/05 04:29:31
updated at 2023/08/05 04:57:05
interface
一般用于类型声明,接口是对象的状态(属性)和行为(方法)的抽象(描述)。这种靠 shape 规范一般称为鸭子类型。
typescript
interface Person {
name: string;
age: number;
}
let tom: Person = {
name: 'Tom',
age: 25,
};
typescript
interface Person {
readonly name: string;
age?: number;
}
typescript
interface Person {
name: string;
age?: number;
[prop: string]: any;
}
const p1: Person = { name: '1' };
const p2: Person = { name: '2', age: 28 };
const p3: Person = { name: '3', sex: 1 };
typescript
// 类型别名:名称唯一,不能重复
type myType = {
name: string;
age: number;
};
const obj: myType = {
name: 'ccc',
age: 33,
};
ts 除对象类型,可以声明(undefined, null, boolean, string,number)类型
在大多数的情况下使用接口类型和类型别名的效果等价,但是在某些特定的场景下这两者还是存在很大区别。
typescript
type PartialPointX = { x: number };
interface Point extends PartialPointX {
y: number;
} // 利用type扩展interface
const obj: Point = {
x: 22,
y: 33,
};
interface PartialPointX {
x: number;
}
type Point = PartialPointX & { y: number }; // 利用interface扩展 type
const obj: Point = {
x: 22,
y: 33,
};
console.log(obj);
// 输出:
// { "x": 22, "y": 33 }