概念:
TypeScript的核心原则之一是对值所具有的结构进行类型检查。 它有时被称做“鸭式辨型法”或“结构性子类型化”。 在TypeScript里,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约
案列
// interface 接口
interface PersonInterface {
name: string;
age: number; // :号 必须要写的
sex?: string; // ?: 可选的
readonly salary: number; // 只读 不能修改
[propName: string]: any; // 任意类型
greet(): void; // void类型像是与any类型相反,它表示没有任何类型。 当一个函数没有返回值时,你通常会见到其返回值类型是 void
}
//接口class中
class People implements PersonInterface {
name: string = '邓紫棋';
age: number = 31;
sex: string= '男';
greet() {
console.log('hello world');
}
}
// interface接口的继承
interface Employee extends PersonInterface {
work: string;
}
const employee: Employee = {
name: '周杰伦',
age: 42,
sex: '男',
work: '前端开发',
greet() {
console.log('hello');
}
};
console.log(employee);