TypeScript - 類別中的 getter 永遠是未定義
我有一個 TypeScript 類別,其中包含一個 getter(它只是多個屬性的連接)。
不知什麼原因,即使裡面的屬性都已定義,getter 總是返回 undefined。
import { IdDisplayName } from './';
export class Person {
id?: number;
age!: number;
personType!: IdDisplayName<number>;
name!: string = '';
public get description() : string {
return this.name + ' • ' + (this.personType.displayName ?? 'No type')
+ '/' + this.age;
}
}
我正在以 JSON 的形式接收數據,並像這樣轉換成 Person:
let person = result as Person;
let desc = person.description; //undefined, never enters the description getter code.
答案#1
類型轉換並不會實例化一個類,它僅僅告訴編譯器將你的 result 當作 Person 類來處理……而實際上可能還不是這樣。
你必須做的,是你大概預期的轉型自己會做的事情,在你的 Person 類別中創建一個 constructor,並使用 new 關鍵字實例化一個 Person 的實例。
export class Person {
constructor(res: any){
// assign properties
}
}
var desc = new Person(result).description;
答案#2
問題是你將結果強制轉換為 person,而不是實例化一個新的 person 實例。這裡是一個可能的修正方法 -
import { IdDisplayName } from './';
export class Person {
constructor(result: 'your result type here') {
this.id = result.id;
this.age = result.age;
this.personType = result.personType;
this.name = result.name;
}
id?: number;
age!: number;
personType!: IdDisplayName<number>;
name = '';
public get description(): string {
return (
this.name +
' • ' +
(this.personType.displayName ?? 'No type') +
'/' +
this.age
);
}
}
那麼它可以這樣使用 -
let person = new Person(result)
