簡體   English   中英

如何在打字稿中從JSON進行轉換期間獲取正確的類?

[英]How to get the proper class during a cast from JSON in typescript?

我的課很簡單

export class Foo {

    name: string;

    index: number;

    toFullString(): string {
        return `${this.name} | ${this.index}`;
    }
}

我從服務器獲取此類的元素,並將json轉換為此類:

.map(response => response.json() as Foo)

現在發生的事情是,在我調用toFullString()方法之后,它失敗了,因為它不是“真正的” Foo對象,就像在C#中那樣。

那么,實現真正的Foo對象的正確方法是什么,最好不需要編寫自己的構造函數等。

TypeScript中的類型安全有時確實是個笑話。

您可以創建對象並為其提供JSON值。

.map(res => this.onResponse(res))

-

function onResponse(res:any){
    this.foo = new Foo();
    this.foo.name = res['name'];
    ...
}

或將JSON值提供給Foo的構造函數

this.foo = new Foo(res['name'], ...);

您要么必須編寫自己的構造函數,要么必須使用返回的對象,並使用for(let obj of responseObjects) { obj['toFullString'] = function ... }附加函數(技術上合法的JS) for(let obj of responseObjects) { obj['toFullString'] = function ... } 一個您不想要的,另一個則有點粗略。

您已經看過的構造方法,但我將在這里重復:

constructor(public name, public index) {
    this.name = name;
    this.index = index;
}

您也可以在地圖中進行相同的操作。

masterFoo: Foo = new Foo();

mapFoo(responseObject: any) {
    <...>
    responseObject['toFullString'] = masterFoo.toFullString;
    <...>
  }

自動映射僅適用於數據對象,這是一個限制,因為JS是所有對象的基礎語言。

這是一個演示如何將函數附加到普通的舊JavaScript對象的插件: http ://plnkr.co/edit/BBOthl0rzjfEq3UjD68I?p=preview

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM