typescript 接口(interface)的两种用法
interface IPerson {
name: string;
age: number;
}
class Person {
constructor(public config: IPerson) {
}
}
var p1 = new Person({
name: "mike",
age:18
})
第一种用法 就有点像自定义类型 送参需要符合interface的接口要求
interface animal {
eat();
}
class sheep implements animal {
eat() {
console.log("吃草")
}
}
class tiger implements animal {
eat() {
console.log("吃肉")
}
}
第二种用法,定义一个动物接口,实现这个接口的类就要实现eat()这个方法
本文深入探讨了 TypeScript 中接口(interface)的两种主要使用场景:一种用于定义对象的形状,确保对象属性的类型正确;另一种用于定义类必须实现的方法,通过实现接口确保类的行为一致性。文章通过具体实例展示了如何使用 interface 来规范参数传递和类的实现。
3441

被折叠的 条评论
为什么被折叠?



