简体   繁体   English

如何在打字稿中从JSON进行转换期间获取正确的类?

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

I have a very simple class 我的课很简单

export class Foo {

    name: string;

    index: number;

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

I get elements of this class from a server and cast json to this class: 我从服务器获取此类的元素,并将json转换为此类:

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

Now what happens is that after I call toFullString() method it fails since this is not the "real" Foo object as it would be in say C#. 现在发生的事情是,在我调用toFullString()方法之后,它失败了,因为它不是“真正的” Foo对象,就像在C#中那样。

So what is the proper way of achieving real Foo object, preferably without the need of writing your own constructors and so on. 那么,实现真正的Foo对象的正确方法是什么,最好不需要编写自己的构造函数等。

The type safety in TypeScript is a joke sometimes really. TypeScript中的类型安全有时确实是个笑话。

You could create the Object and give it the JSON values. 您可以创建对象并为其提供JSON值。

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

- -

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

Or give the JSON values to the constructor of Foo 或将JSON值提供给Foo的构造函数

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

Either you're going to have to write your own constructor or you'll have to take your returned obejcts and append the function (technically legal JS) with for(let obj of responseObjects) { obj['toFullString'] = function ... } . 您要么必须编写自己的构造函数,要么必须使用返回的对象,并使用for(let obj of responseObjects) { obj['toFullString'] = function ... }附加函数(技术上合法的JS) for(let obj of responseObjects) { obj['toFullString'] = function ... } One you don't want, and the other is a little sketchy. 一个您不想要的,另一个则有点粗略。

The constructor method you have already seen but I'll repeat here: 您已经看过的构造方法,但我将在这里重复:

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

You could also do it in the map which is the same thing. 您也可以在地图中进行相同的操作。

masterFoo: Foo = new Foo();

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

The auto mapping works for data objects only, and it's a limitation due to JS being the underlying language of it all. 自动映射仅适用于数据对象,这是一个限制,因为JS是所有对象的基础语言。

Here's a plunker demonstrating appending the function to a Plain Old JavaScript Object: http://plnkr.co/edit/BBOthl0rzjfEq3UjD68I?p=preview 这是一个演示如何将函数附加到普通的旧JavaScript对象的插件: http ://plnkr.co/edit/BBOthl0rzjfEq3UjD68I?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM