如何在打字稿中从JSON进行转换时获取正确的类? [英] How to get the proper class during a cast from JSON in typescript?

查看:33
本文介绍了如何在打字稿中从JSON进行转换时获取正确的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课很简单

 导出类Foo {名称:字符串;索引号;toFullString():字符串{返回`$ {this.name} |$ {this.index}`;}} 

我从服务器获取此类的元素,并将json转换为此类:

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

现在发生的是,在我调用 toFullString()方法之后,它失败了,因为它不是真正的" Foo 对象,就像在C#中那样./p>

那么实现真正的 Foo 对象的正确方法是什么,最好不需要编写自己的构造函数等.

TypeScript中的类型安全有时确实是个笑话.

解决方案

要么您将不得不编写自己的构造函数,要么必须使用返回的对象并将函数(技术上合法的JS)添加为<代码> for(让responseObjects的obj){obj ['toFullString'] =函数...} .一个你不想要的,另一个有点粗略.

您已经看到过的构造方法,但在这里我将重复:

 构造函数(公共名称,公共索引){this.name =名称;this.index =索引;} 

您也可以在地图上进行同样的操作.

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

自动映射仅适用于数据对象,由于JS是所有语言的基础,因此存在局限性.

这是一个小矮人,展示了将该函数附加到一个普通的旧JavaScript对象上: http://plnkr.co/edit/BBOthl0rzjfEq3UjD68I?p=preview

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:

.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#.

So what is the proper way of achieving real Foo object, preferably without the need of writing your own constructors and so on.

The type safety in TypeScript is a joke sometimes really.

解决方案

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 ... }. 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.

Here's a plunker demonstrating appending the function to a Plain Old JavaScript Object: http://plnkr.co/edit/BBOthl0rzjfEq3UjD68I?p=preview

这篇关于如何在打字稿中从JSON进行转换时获取正确的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆