Search code examples
typescriptkeyof

it is possible to use keyof to update object in typescript?


i want to implementation a function to update object like this.


interface Object {
   name: string
   age: number
}

let obj = {}

function updateObject(key: keyof Object, value: ???) {
   obj[key] = value;
}

It is possible in typescript? and what i should input at ???


Solution

  • You can use generics to say that key is a key of Object and value is the type of that key

    interface Object {
       name: string
       age: number
    }
    
    let obj: Object = {};
    
    function updateObject<K extends keyof Object>(key: K, value: Object[K]) {
       obj[key] = value;
    }
    
    updateObject('name', 'foo'); // Fine
    updateObject('name', 1); // Error
    updateObject('age', 'foo'); // Error
    updateObject('age', 1); // Fine