방금 Typescript로 시작했는데 클래스 속성이 클래스에 선언 된 속성 외에도 임의의 속성을 보유하는 객체 일 수 있는지 이해할 수 없습니다. 예를 들어 name
을 Person
의 속성으로 정의한 다음 properties
아래에 해당 키와 같은 다른 임의의 특성을 정의 할 수 있어야합니다. 제법클래스 속성으로 임의의 속성을 가진 객체
Property 'height' does not exist on type 'Object'
를 : 말하는 괜찮 간다 할당하지만, 라인 (12)에 액세스를 시도 할 것으로 보인다 오류가 발생합니다! 나는 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);
인터페이스의 또 다른 대안을 , 그것은 여전히 작동하지 않습니다. Person#properties
의 정적 유형은 유형 검사 그것에 대해 추가 유형의 정보를 유지하지 않습니다 단순히 Object
때문에 당신이 컴파일 에러가 발생하는 이유
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