Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading