Home > Net >  Fit a object into interface dynamically
Fit a object into interface dynamically

Time:07-15

I would like to get a data from a :any object and insert it into the :iInterface in typescript

This example obj:

 name: "Gulherme",
 Query: "test",
 id: 2,
 namespace: "Test"

Insert and generate into this interface:

interface Test{
    name:string,
    id:number
}

The obj is dynamically loaded.

I did something like that but with no success.

var result:Test= obj as Test;

Expected result:

result = {
   name: "Gulherme",
   id: 2
}

The field from obj that doesn't match with the interface, can be deleted.

CodePudding user response:

Yes you can. I made it a bit more dynamic so you can choose the keys you want.

// takes any object and keys of the specified generic.
function pick<T>(obj: any, ...keys: (keyof T)[]): Pick<T, typeof keys[number]> {
    // object into which the key-value pairs will be added
    let object: any = {};
    // loop over the passed object by transforming it into
    // an array of entries ([key, value]).
    return Object.entries(obj).reduce((acc, entry) => {
        const entryKey = entry[0] as keyof T;
        // only add the key-value pair of the passed object 
        // if it is in the specified keys.
        if (keys.includes(entryKey)) {
            acc[entryKey] = entry[1];
        }
        return acc;
    }, object);
}

pick<Test>(obj, "id", "name");

You could wrap this in another function if it's always those keys for the test object that you want - specifiying obj to then structurally conform to Test would make sense here, unless you want to randomly pass objects in and be fine with empty return (thanks @Juan Mendes):

function transformToTest(obj: Test) {
    return pick<Test>(obj, "id", "name");
}`

If you want to pass the keys as an array, change the signature of the function to look like this:

function pick<T>(obj: any, keys: (keyof T)[]): Pick<T, typeof keys[number]>

If the keys don't exist it will return an empty object.

Check this playground

  • Related