TypeScript 接口知识点详解
TypeScript 接口知识点详解
在 TypeScript 中,接口(Interfaces)是一种强大的方式来定义对象的形状。接口可以用于定义对象的结构,同时也可以用来定义函数和类的结构。以下是 TypeScript 中接口的详细知识点:
1. 定义接口
接口是通过关键字 interface
来定义的,它描述了对象应该包含哪些属性和方法:
interface Person {name: string;age: number;
}
2. 实现接口
当一个类实现一个接口时,它必须提供接口中定义的所有属性和方法:
class User implements Person {name: string;age: number;constructor(name: string, age: number) {this.name = name;this.age = age;}
}
3. 可选属性
接口中的属性可以是可选的,使用 ?
标记:
interface Person {name: string;age?: number; // 可选属性
}
4. 只读属性
接口中的属性可以是只读的,使用 readonly
关键字标记:
interface Person {readonly id: number;name: string;
}
5. 索引签名
接口可以包含索引签名,这允许你定义一个对象,其属性是动态的,但值的类型是固定的:
interface StringArray {[index: number]: string;
}
6. 扩展接口
接口可以通过使用 extends
关键字来扩展其他接口:
interface Person {name: string;
}interface Employee extends Person {id: number;
}
7. 合并接口
接口可以被合并,这意味着你可以在不同的接口中定义相同的属性,然后合并它们:
interface Person {name: string;
}interface Person {age: number;
}let person: Person = {name: "Kimi",age: 30,
};
8. 函数类型
接口可以描述函数的形状,包括参数类型和返回值类型:
interface GreetFunction {(name: string): void;
}const greet: GreetFunction = function(name) {console.log("Hello, " + name);
};
9. 类类型
接口可以描述类的构造函数和其实例类型:
interface ClockConstructor {new (hour: number, minute: number): ClockInterface;
}interface ClockInterface {tick(): void;
}class Clock implements ClockConstructor {constructor(h: number, m: number) {}tick() {}
}
10. 接口继承类
接口可以继承类的成员,但不能继承其实现:
class Control {hello: string = "hello";
}interface SelectableControl extends Control {select(): void;
}class Button extends Control implements SelectableControl {select() {}
}
11. 接口与类型别名
虽然接口和类型别名(type aliases)都可以定义对象的形状,但它们之间有一些差异。例如,类型别名可以定义基本类型、联合类型、元组等,而接口不能。另外,接口可以被扩展,而类型别名不能。
12. 空接口
空接口不包含任何属性,它等价于 any
类型,但通常用于表示一个值可以是任何类型:
interface EmptyInterface {}function warn(user: EmptyInterface) {console.log("This is a warning message");
}
接口是 TypeScript 中定义和使用类型的一种非常灵活和强大的方式,它们为代码的结构和行为提供了清晰的约束。通过使用接口,你可以提高代码的可维护性和可读性。