Home > Back-end >  Dynamically modify object property typescript
Dynamically modify object property typescript

Time:05-05

I have the following typescript function, the purpose of this function is to modify the property of an object dynamically :

const test = (data: any, propertyName: keyof Test1, x: Test1) => {
    x[propertyName] = data;
}

Here is the "Test1 type"

type Test1 = {
    test: string;
    test1: number;
    test2: string;
}

In my "test" function, it gives me the following error :

Type 'any' is not assignable to type 'never'

I guess the problem comes from the type of "data" but I don't know how I can change it. Thanks for your help !

CodePudding user response:

You need to tell TypeScript that the type of data is Test1[propertyName]:

const test = <K extends keyof Test1>(data: Test1[K], propertyName: K, x: Test1) => {
    x[propertyName] = data;
};

You can't use Test1[propertyName] directly, Test1[typeof propertyName] won't work because that's the same as Test1[keyof Test1], so you need a generic to retain the type information of propertyName and use it later for the type of data.

Playground

  • Related