简体   繁体   中英

Typescript casting object to a class ignoring properties

I have an object that I am trying to cast from my webapi call.

So lets say this is the data from the 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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