Search code examples
typescriptobjecttypes

construct a object from array and achieve tab completion


need to use values from an array as keys to create a new object.

And need to achieve tap completion.

const keys = ['name', 'age', 'contact', 'response'];
let obj = {};
keys.forEach(key => {
    obj[key] = row[key];
});
obj. //need to know what are the properties previously added.

Typescripts need to understand the object's name, age, and contact properties.


Solution

  • 
    // `as const` makes strings be string literals
    const keys = ['name', 'age', 'contact', 'response'] as const;
    // theese are the keys union ('name' | 'age' | ...)
    type KeyType = typeof keys[number]
    // row has data on what object will be
    type RowType = typeof row
    // the `obj` is the copy of `row` with only `keys` keys
    type FullObjType = Pick<RowType, KeyType>
    // the `obj` properties are not set yet
    type ObjType = Partial<FullObjType>
    
    let obj: ObjType = {};
    for (let k of keys) {
      obj[key] = row[key]
    }
    let fullObj: FullObjType = obj;
    

    Or the other way,

    
    function PickKeys<T, K extends keyof T>(row: T, keys: K[]) {
       return Object.fromEntries(keys.map(k => [k, row[k]])) as Pick<T, K>
    }