Morteza Ebrahimi
Morteza Ebrahimi

Reputation: 760

Cast an object to a model in typescript

I have a json like lst in below example, and I wanna map it to MyModel.

interface MyModel { 
    id: number;
    isRequired : boolean;
    ,...
}

let lstByModel: Array<MyModel> = [];

// lst comes from API
let lst:any[] = [
    {
        "id":"10",
        "isRequired":"false"        
    }
];

lstByModel = lst; // How to map lst to MyModel (lstByModel)?

console.log(lstByModel); // it shows { id : "10" , isRequired : "false"} but I need { id : 10, isRequired : false } How can I do that?

thanks in advance.

Upvotes: 1

Views: 3804

Answers (4)

derelict
derelict

Reputation: 2082

if you can use classes for your models instead of interfaces, here's an Object.assign() pattern that might work for you. also a good pattern for other api- or io-related translations / functionality.

abstract class ApiLoadable {
 static fromObject<T extends ApiLoadable>(this: { new(): T }, obj: object): T {
   return Object.assign(new this(), obj);
 }
}

class MyModel extends ApiLoadable {
  id: number;
  isRequired : boolean;
}

const json = `{ "id": 10, "isRequired": false }`;
const model = MyModel.fromObject(JSON.parse(json));

notice there's a bit of 'this' parameter trickery in the static method -- this lets the static method always create the correct subclass instance, based on this question about that subject

Upvotes: 1

amitdigga
amitdigga

Reputation: 7168

types or iterfaces in Typescript are compile time only. So your lst will not be converted to any other type automatically.

You need to manually map string to number. In your case

lstByModel = lst.map(lstItem=>{
    return {
         id:parseInt(lstItem.id), // manually changing string to number
        isRequired: lstItem.isRequired=="true" //parsing boolean
    }
})

Upvotes: 1

Chandan Y S
Chandan Y S

Reputation: 1078

let lst:any[] = [ { "id":"10", "isRequired":"false" } ]; 

As shown in your json format, the id and isRequired fields is type of string.

Hence what you need to do is, convert id to number and isRequired to boolen using foreach loop.

Upvotes: 0

kunal verma
kunal verma

Reputation: 486

You can use Object.assign()

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Upvotes: 2

Related Questions