栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将JSON对象解析为TypeScript对象

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将JSON对象解析为TypeScript对象

编译器允许您将返回的对象强制

JSON.parse
转换为类的原因是因为typescript基于结构子类型。
您实际上并没有的实例
Employee
,而是拥有一个具有相同属性的对象(如在控制台中看到的)。

一个简单的例子:

class A {    constructor(public str: string, public num: number) {}}function logA(a: A) {    console.log(`A instance with str: "${ a.str }" and num: ${ a.num }`);}let a1 = { str: "string", num: 0, boo: true };let a2 = new A("stirng", 0);logA(a1); // no errorslogA(a2);

(操场上的代码)

没有错误是因为

a1
满足类型,
A
因为它具有所有属性,并且只要它具有相同的属性,
logA
即使函数接收的实例不是该函数的实例,也可以在没有运行时错误的情况下调用该函数
A

当您的类是简单的数据对象并且没有方法时,这很好用,但是一旦您引入了方法,事情就会崩溃:

class A {    constructor(public str: string, public num: number) { }    multiplyBy(x: number): number {        return this.num * x;    }}// this won't compile:let a1 = { str: "string", num: 0, boo: true } as A; // Error: Type '{ str: string; num: number; boo: boolean; }' cannot be converted to type 'A'// but this will:let a2 = { str: "string", num: 0 } as A;// and then you get a runtime error:a2.multiplyBy(4); // Error: Uncaught TypeError: a2.multiplyBy is not a function

(操场上的代码)


编辑

这很好用:

const employeeString = '{"department":"<anystring>","typeOfEmployee":"<anystring>","firstname":"<anystring>","lastname":"<anystring>","birthdate":"<anydate>","maxWorkHours":0,"username":"<anystring>","permissions":"<anystring>","lastUpdate":"<anydate>"}';let employee1 = JSON.parse(employeeString);console.log(employee1);

(操场上的代码)

如果您尝试

JSON.parse
在不是字符串的对象上使用它:

let e = {    "department": "<anystring>",    "typeOfEmployee": "<anystring>",    "firstname": "<anystring>",    "lastname": "<anystring>",    "birthdate": "<anydate>",    "maxWorkHours": 3,    "username": "<anystring>",    "permissions": "<anystring>",    "lastUpdate": "<anydate>"}let employee2 = JSON.parse(e);

然后,您将收到错误消息,因为它不是字符串,而是对象,如果您已经以这种形式使用它,则无需使用

JSON.parse

但是,正如我所写的那样,如果您采用这种方式,那么您将没有类的实例,只有一个具有与类成员相同属性的对象。

如果您想要一个实例,那么:

let e = new Employee();Object.assign(e, {    "department": "<anystring>",    "typeOfEmployee": "<anystring>",    "firstname": "<anystring>",    "lastname": "<anystring>",    "birthdate": "<anydate>",    "maxWorkHours": 3,    "username": "<anystring>",    "permissions": "<anystring>",    "lastUpdate": "<anydate>"});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/399840.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号