1.什么是接口
用于约束类、对象、函数的标准
2.接口的使用
(1)约束对象
1 interface IFullName { 2 firstName:string, 3 lastName:string 4 } 5 const fullName = ({firstName,lastName}:IFullName):string =>{ 6 return firstName + lastName 7 }
对象接口可以用来描述对象的形状结构
1 interface IVegetables { 2 readonly color:string, 3 size:string 4 } 5 interface IVegetables{ 6 age?:number, // ?标识的属性为可选属性 7 taste:'sour'|'sweet' 8 } 9 const tomato:IVegetables = { 10 color:'red', 11 size:'10', 12 taste:'sour' 13 } 14 tomato.color = 'green'; // 仅读属性不能进行修改
(2)约束函数
interface IFullName { firstName:string, lastName:string }
// 接口约束函数 interface IFn { (obj:IFullName):string } const fullName:IFn = ({firstName,lastName})=>{ return firstName + lastName }
(3)约束类
interface Speakable { name:string; speak():void; } interface ChineseSpeakable{ speakChinese():void }
// 接口实现类 需要用到implements关键字 class Speak implements Speakable,ChineseSpeakable{ name!:string speak(){} speakChinese(){} }
3.接口和类型别名的区别
// 约束对象和函数时,也可以使用类型别名来实现
type IFullName = {
firstName: string;
lastName: string;
};
type IFn = (obj: IFullName) => string;
const fullName: IFn = ({ firstName, lastName }) => {
return firstName + lastName;
};
那它们之间有什么区别呢?
共同点:
都不会出现在编译结果中
不同点:
1.类型别名不能约束类,接口可以约束类
2.类型别名不能继承,接口可以实现继承
interface Speakable { speak():void } interface SpeakChinese extends Speakable{ speakChinese():void } class Speak implements SpeakChinese{ speakChinese(): void { throw new Error("Method not implemented."); } speak(): void { throw new Error("Method not implemented."); } }

浙公网安备 33010602011771号