Home > Mobile >  Create generic TypeScript function that will assign a value to object property
Create generic TypeScript function that will assign a value to object property

Time:02-02

I want to create a simple function that will take key of a specific object and value for the respective key and assign the new value to the object. Something like this:

interface MyObject {
    key1: string
    key2: number
}

const object: MyObject = {
    key1: 'abc',
    key2: 100
}

const updateObjectProperty = (key: keyof MyObject, value: MyObject[keyof MyObject]) => {
    object[key] = value
}

But in this case - it's not working. TypeScript complier shows an error:

Type 'string | number' is not assignable to type 'never'.

I feel like maybe some generics could potentially resolve the problem here, but I'm struggling to figure out how.

CodePudding user response:

If you tie the parameters together using a generic type parameter, it will compile:

const updateObjectProperty = <K extends  keyof MyObject>(key: K, value: MyObject[K]) => {
    object[key] = value
}

updateObjectProperty("key1", "") //ok
updateObjectProperty("key2", "") // err
updateObjectProperty("key2", 2) // ok

enter image description here

CodePudding user response:

can you try

const updateObjectProperty = <T extends keyof MyObject>(key: T, value: MyObject[T]) => {
    object[key] = value
}
  •  Tags:  
  • Related