Home > Blockchain >  Create a new subset object from array of keys with the correct type infer
Create a new subset object from array of keys with the correct type infer

Time:11-09

Given an object and a string array of keys (these keys will exist in the object), construct a new object containing those keys and its corresponding value with the correct Typescript typing. That is:

/**
 * This function will construct a new object
 * which is the subset values associated to 
 * the keys array
**/
function extractFromObj<T>(obj: T, keys: (keyof T)[])

// in here, suppose `post` is a huge object,
// but the intellicence should only show keys
// from the keys array
const { id, properties, created_time } = extractFromObj(post, ['id', 'properties', 'created_time'])

My solution (wrong so far)

function extractFromObj<T>(obj: T, keys: (keyof T)[]): Record<keyof typeof keys, any> {
  return keys.reduce((newObj, curr) => {
    newObj[curr] = obj[curr]

    return newObj
  }, {} as Record<keyof typeof keys, any>)
}

const {} = extractFromObj(post, ['id', 'properties', 'created_time']) // wrong

Assistance needed please & thank you

  • Related