简体   繁体   English

打字稿将对象转换为忽略属性的类

[英]Typescript casting object to a class ignoring properties

I have an object that I am trying to cast from my webapi call.我有一个我试图从我的 webapi 调用中投射的对象。

So lets say this is the data from the webapi所以让我们说这是来自 webapi 的数据

let userTestStatus: { id: number, name: string }[] = [
    { "id": 0, "name": "Available", "date" : "01/01/2001" },
    { "id": 1, "name": "Ready", "date" : "01/01/2001" },
    { "id": 2, "name": "Started", "date" : "01/01/2001" }
];

This is my typescript Class.这是我的打字稿类。 As you can see there is no date property如您所见,没有日期属性

export myClass{
  id: number;
   name: string;
}

When the object is converted the date property is there even though it doesn't exist in my class.当对象被转换时,日期属性在那里,即使它在我的类中不存在。 How can I get typescript to ignore properties that do not exist in the class?如何让打字稿忽略类中不存在的属性?

You can map all of your objects just to such model which you would like to have您可以将所有对象映射到您想要的模型

const myModelObejctsArray: MyModel[] = userTestStatus.map(user => {
   return {
    id: user.id,
    name: user.name
   }
})

Your data fulfills the given type interface.您的数据满足给定的类型接口。 However, your data has even more properties than you declared as a type.但是,您的数据具有比您声明为类型更多的属性。

Your Typescript IDE should display you some message that the objects in your array do not specifically have a date property.您的 Typescript IDE 应该向您显示一些消息,说明您的数组中的对象没有专门的日期属性。 But you can still run it.但是你仍然可以运行它。

If you do not want the date property in your array elements, you could delete it on your own:如果您不想在数组元素中使用 date 属性,您可以自行删除它:

userTestStatus.forEach(e => delete e.date);

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

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