Home > OS >  it is possible to use keyof to update object in typescript?
it is possible to use keyof to update object in typescript?

Time:06-25

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 ???

CodePudding user response:

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
  • Related