1

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

Terriermon
  • 71
  • 6

1 Answers1

3

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
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50