返回
TypeScript 进阶用法:揭秘接口与类型别名背后的秘密
前端
2024-01-26 19:48:19
TypeScript 接口
接口是 TypeScript 中定义对象或函数形状的一种方式。接口可以包含属性、方法、构造函数签名和其他成员。一个接口可以被多个对象实现,而实现该接口的对象必须符合接口定义的形状。
接口的基本用法
// 定义一个接口
interface Person {
name: string;
age: number;
}
// 实现接口
class Student implements Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
// 使用接口
const student: Student = new Student('John', 20);
console.log(student.name); // John
console.log(student.age); // 20
扩展接口
接口可以被其他接口扩展。扩展接口可以继承父接口的属性、方法、构造函数签名和其他成员。
// 定义父接口
interface Animal {
name: string;
age: number;
}
// 定义子接口,继承父接口
interface Dog extends Animal {
breed: string;
}
// 实现子接口
class GoldenRetriever implements Dog {
name: string;
age: number;
breed: string;
constructor(name: string, age: number, breed: string) {
this.name = name;
this.age = age;
this.breed = breed;
}
}
// 使用子接口
const dog: GoldenRetriever = new GoldenRetriever('Lucky', 5, 'Golden Retriever');
console.log(dog.name); // Lucky
console.log(dog.age); // 5
console.log(dog.breed); // Golden Retriever
可缺省属性
接口可以包含可缺省属性。可缺省属性是指在实现接口时,可以不提供该属性的值。
// 定义接口,包含可缺省属性
interface Person {
name: string;
age?: number; // 可缺省属性
}
// 实现接口
class Student implements Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
// 使用接口
const student: Student = new Student('John');
console.log(student.name); // John
console.log(student.age); // undefined
只读属性
接口可以包含只读属性。只读属性是指在实现接口时,只能给该属性赋值一次。
// 定义接口,包含只读属性
interface Person {
readonly name: string;
}
// 实现接口
class Student implements Person {
readonly name: string;
constructor(name: string) {
this.name = name;
}
}
// 使用接口
const student: Student = new Student('John');
student.name = 'Mary'; // 报错:只读属性不能被修改
接口定义函数类型(可执行类型)
接口可以定义函数类型。函数类型是指具有特定参数类型和返回值类型