简体   繁体   English

如何从TypeScript中的匿名对象轻松创建强类型对象?

[英]How can I easily create a strongly typed object from an anonymous object in TypeScript?

I have some JSON containing anonymous objects coming to my client-side. 我有一些JSON包含来自我的客户端的匿名对象。 Is there some built-in mechanism or external library for converting these anonymous objects into strongly-typed TypeScript objects? 是否有一些内置机制或外部库用于将这些匿名对象转换为强类型的TypeScript对象? Is there something like AutoMapper for doing this? 是否有像AutoMapper这样的东西?

My objects are complex types, with complex types as properties. 我的对象是复杂类型,复杂类型作为属性。

Get some sample data and place it in a .ts file: 获取一些示例数据并将其放在.ts文件中:

var people = [
    {
        "name": "bob", "height": 150, "pets": [{ "name": "spot", "species": "dog" }]
    },
    {
        "name": "jane", "height": 142, "pets": [{ "name": "lucy", "species": "cat" }]
    }
];

Run tsc --declaration yourFile.ts 运行tsc --declaration yourFile.ts

Now you'll have yourFile.d.ts : 现在你将拥有yourFile.d.ts

declare var people: {
    "name": string;
    "height": number;
    "pets": {
        "name": string;
        "species": string;
    }[];
}[];

Replace declare var people: with interface Person , remove the trailing [] , and (optionally) remove the quotes: 替换declare var people: with interface Person ,删除trailing [] ,并(可选)删除引号:

interface Person {
    name: string;
    height: number;
    pets: {
        name: string;
        species: string;
    }[];
}

Recently I created an AutoMapper implementation in TypeScript / JavaScript exactly for this scenario. 最近我在TypeScript / JavaScript中为这个场景创建了一个AutoMapper实现。 I have put the code at GitHub ( AutoMapperTS ). 我把代码放在GitHub( AutoMapperTS )上。 You can also use the library directly using the automapper-ts NPM package or automapper-ts Bower package. 您也可以使用automapper-ts NPM软件包或automapper-ts Bower软件包直接使用该库。

The library is almost fully documented. 该库几乎完全记录在案。 Furthermore, quite a lot of Jasmine unit tests are already available (code coverage is over 90%). 此外,已有相当多的Jasmine单元测试可用(代码覆盖率超过90%)。 They should provide you with some explanation of needed. 他们应该为您提供所需的一些解释。

I hope this library suits your needs. 我希望这个库适合您的需求。 Should you have any questions and/or remarks, please don't hesitate contacting me! 如果您有任何问题和/或评论,请不要犹豫与我联系!

Happy coding! 快乐的编码!

I was looking for an easy way to convert json data from a web service to an interface too. 我一直在寻找一种简单的方法将json数据从Web服务转换为接口。 Didn't found what I need but here is my solution. 没找到我需要的东西,但这是我的解决方案。 Noticed that I added a "Pet" interface and added another pet to your json. 注意到我添加了一个“Pet”界面,并为你的json添加了另一个宠物。 Also had to specify the anonymous object as "any". 还必须将匿名对象指定为“any”。 You can cut/paste this to TypeScript playground ( http://www.typescriptlang.org/play/index.html ) to see the results. 您可以将其剪切/粘贴到TypeScript playground( http://www.typescriptlang.org/play/index.html )以查看结果。 Hope this helps. 希望这可以帮助。

let header = document.createElement("div");
header.textContent = "Test";
document.body.appendChild(header);

var people:any = [
    {
        "name": "bob", "height": 150, "pets": [{ "name": "spot", "species": "dog" }, {"name" : "violet", "species": "shark"}]
    },
    {
        "name": "jane", "height": 142, "pets": [{ "name": "lucy", "species": "cat" }]
    }
];

interface Pet {
    name: string;
    species: string;
}
interface Person {
    name: string;
    height: number;
    pets: Array<Pet>
}

class Foo {
    convertToObject = (person: Person) => person;
}


var person = new Foo().convertToObject(people[0]);

let div = document.createElement("div");
div.textContent = `hey ${person.name} I see you have ${person.pets.length} pet`;
document.body.appendChild(div);

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

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