interface接口,TypeScript使用接口定义数据类型
类可以实现接口,接口之间可以相互继承
接口只是TypeScript在开发过程中帮助做语法提示的工具,编译成JavaScript时,会把接口、类型相关内容剔除。
/**
* ? 可选属性
* readonly 只读属性
* [propName] 其他属性
*/
interface Person {
name: string;
age?: number;
readonly info: string;
[propName: string]: any;
sayHello(): string;
}
// extends 接口继承
interface Teacher extends Person{
teach(): string;
}
// implements 接口实现
class User implements Person {
name = 'Brady';
info = 'message';
sayHello() {
return 'Hello World';
}
};
// 接口定义函数类型
interface SayHi {
(word: stirng): string;
}
const say: SayHi = (word: string) => {
return word;
};
注:interface 和 type 相类似,但并不完全一致
- type 可以定义基础类型,例如 type Message = string;
- interface 可以设置可选?、只读readondy、其他[propName]
- interface 可以使用继承extends、可以被实现implements