TypeScript 转换 json 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41954751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript casting json array
提问by miechooy
I have JSON array as below:
我有如下 JSON 数组:
var json = [{
id: 1,
login: "Mieszko",
name: "Misztal",
surname: "Adminek",
phone: "0413414",
role: 2
},
{
id: 2,
login: "Rafal",
name: "Robak",
surname: "Kierowczek",
phone: "5145145",
role: 1
}
];
I have also created User class as below:
我还创建了 User 类,如下所示:
export class User extends BaseModel {
id: number;
login: string;
name: string;
surname: string;
phone: string;
roles: Roles;
admin: boolean;
driver: boolean;
isDriver(): boolean {
return this.roles === 1;
}
//other methods
}
My plan is to cast incomming JSON array to User array. Inside JSON I get role as integer. I have admin and driver boolean fields in my class. This is needed in ngModel for checkboxes.
我的计划是将传入的 JSON 数组转换为 User 数组。在 JSON 中,我将角色作为整数。我的班级中有 admin 和 driver 布尔字段。这在 ngModel 中需要用于复选框。
Now the problem is after this line
现在问题是在这一行之后
var users: Array<User> = JSON.parse(JSON.stringify(json));
I cannot call method from User class e.g users[0].isDriver()
because compiler doesn't recognize isDriver() method.
我无法从 User 类调用方法,例如users[0].isDriver()
因为编译器无法识别 isDriver() 方法。
Does anyone know how to solve this?
有谁知道如何解决这个问题?
回答by Jakub Synowiec
TypeScript type assertions
TypeScript 类型断言
TypeScript allows you to override its inferred and analyzed view of types any way you want to. This is done by a mechanism called "type assertion".
TypeScript 允许您以任何方式覆盖其推断和分析的类型视图。这是通过称为“类型断言”的机制完成的。
Type assertions have two forms. One is the "angle-bracket" syntax:
类型断言有两种形式。一种是“尖括号”语法:
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
And the other is the as-syntax:
另一个是 as 语法:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Answer to this question
回答这个问题
In your case the problem is not the type assertion though. You are trying to assigning an array of plain JSON objects to users variable and then trying to call a method that doesn't exist on an object (users[0].isDriver is undefined).
在您的情况下,问题不在于类型断言。您正在尝试将一组纯 JSON 对象分配给 users 变量,然后尝试调用对象上不存在的方法(users[0].isDriver 未定义)。
You can't simply cast a plain object to a JavaScript/TypeScript class instance. You have to instantiate a User first. There are a number of techniques for doing it, and generally involve copying data.
您不能简单地将普通对象转换为 JavaScript/TypeScript 类实例。你必须先实例化一个用户。有许多技术可以做到这一点,通常涉及复制数据。
For an example solution of "casting" a JSON to an instance of TS class please see one of the following answers:
有关将 JSON“投射”到 TS 类的实例的示例解决方案,请参阅以下答案之一: