声明
interface Point {x: number;y: number;z?: number;readonly k: number;[key: string]: string;}
声明混合类型
interface Invoker {(): void;fn: () => void;}const invoker: Invoker = function () {invoker.fn();}invoker.fn = () => console.log(111);invoker();
相同名称接口会合并
interface Point {x: number;y: number;}let point: Point;interface Point {z: number;}point.z
接口可以继承,方便扩展
interface Point {x: number;y: number;}interface MyPoint extends Point {z: number;}let point: MyPoint;point.z
接口声明类类型
interface Class {new(...args: any[]): any}
接口声明函数
interface IFunc {(name: string, age: number): void}const func: IFunc = function (name: string, age: number) {}
总结
类可以适用于混合类型(函数上的属性,type 无法描述)的场景,以及更方便继承扩展,除了联合类型都建议使用 interface 而非 type,接口不支持联合类型(string | number)
