0

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 !

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.