考虑下面的类:
class Person {
name: string = 'Shachar';
age: number = 22;
printPerson() {
console.log(`name: ${this.name}, age: ${this.age}`);
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法获得一个具有此类实例“拥有”的属性的接口?在此示例中,我只需要属性name和age,因为printPerson最终将成为任何实例原型的一部分,而不是自己的属性。
需要明确输入“姓名”和“年龄”的解决方案是不可接受的,因为该类可能有许多属性,而我只想将它们写入一次。
感觉应该有一个更好的答案,也许有,但作为一种解决方法,您可以将示例类分成两个单独的类 - 一个包含您的属性,另一个包含您的方法?例如:
class PersonProperties {
name: string = 'Shachar';
age: number = 22;
}
class Person extends PersonProperties {
printPerson() {
console.log(`name: ${this.name}, age: ${this.age}`);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以利用 PersonProperties 的隐式接口或创建您认为合适的自定义接口,例如
interface IPersonProperties extends PersonProperties {};
var x:IPersonProperties = {
age: 500000,
name: ""
}
Run Code Online (Sandbox Code Playgroud)
也许不理想,但它应该有效。
| 归档时间: |
|
| 查看次数: |
1328 次 |
| 最近记录: |