Common properties from two interfaces using generic

Viewed 29
interface userDetails{
      name:string;
      age:number;
    }
    interface json{
        name:string;
        age:number;
        address:string
    }
export function createListItems<K,l>(jsonData:K[]): l[]{
    let items: l[] = [];
    type P=keyof l;
    for(let i=0; i<jsonData.length; i++){
        let obj:Partial<Record<P,l[P]>>={};
           ...I want to fetch only l properties(name,age) from k(name,age,addrees) and store it in obj. how can I do that.
    }
    .
    items.push(obj as l);
    return items;
}
createListItems<json,userDetails>({[name:"sunny",age:20,address:"pune"],[name:"minnu",age:20,address:"pune"]});

I want to fetch useDetails interface properties from json interface and push it to array. How to do that with generic approach. Something like let obj:Partial<Record<keyof l,string|boolean>={} At the end obj need to have name and age properties fetched from json interface.

1 Answers

You can use lodash pick method here. The _.pick() method is used to return a copy of the object that is composed of the picked object properties.

import { keys } from 'ts-transformer-keys';

const keysOfL = keys<l>();

console.log(_.pick(obj, keysOfL));

Once you have the keys you care about you can write a pick() function that pulls just those properties out of an object:

function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {
  return keys.reduce((o, k) => (o[k] = obj[k], o), {} as Pick<T, K>);
}

And them we can use it on your test object to get reduced:

interface MyInterface {
  test: string;
}
interface MyTest {
  test: string;
  newTest: string;
}    
var test: MyTest = { test: "hello", newTest: "world" }
    
    const reduced: MyInterface = pick(test, ...myTestKeys);
    
    console.log(JSON.stringify(reduced)); // {"test": "hello"}

That works!

Reference.

Related