我刚刚开始使用Typescript,并且我无法理解是否有可能将类属性作为对象,除了在类中声明的属性之外,该对象将包含任何任意属性。例如,我在此将name
定义为Person
的属性,然后在properties
下,您应该能够为该人定义任何其他任意特征,例如其高度。看起来,分配它没问题,但试图访问它在第12行抛出一个错误说:具有任意属性作为类属性的对象
Property 'height' does not exist on type 'Object'
公平的够了!我知道不能保证一个名为height
的属性可能只是一个对象,但仍然应该有办法做到这一点。
下面是代码:
class Person {
public name: string;
public properties: Object;
constructor(name: string, other: Object) {
this.name = name;
this.properties = other;
}
}
let props: Object = { height: 200 };
var nick = new Person("Bob", props);
console.log(nick.properties.height);
这里是我试过的替代,它抛出一模一样的错误:
class Person {
public name: string;
public properties: Object;
constructor(name: string, other:{ height: number }) {
this.name = name;
this.properties = other;
}
}
var nick = new Person("Bob", { height: 200 });
console.log(nick.properties.height);
与接口另一种选择我只是试着,那仍然不起作用。
interface PersonProperties {
height: number;
}
class Person {
public name: string;
public properties: Object;
constructor(name: string, other: PersonProperties) {
this.name = name;
this.properties = other;
}
getHeight(): number {
return this.properties.height;
}
}
var properties: PersonProperties = { height: 200 };
var nick = new Person("Bob", properties);
document.write(nick.getHeight().toString());
你可以将其定义为任何类型 – Geeky