Qwertiy
Qwertiy

Reputation: 21400

Assign a property of an object with properties of different type

This code was valid in 3.3.3, but fails to compile in 3.5.1 and newer. How can I fix it? Playground.

interface IData {
  a: string;
  b: number;
}

var form: IData = { a: "", b: 0 };

function doSmth(field: keyof IData, value: any) {
  form[field] = value; // Type 'any' is not assignable to type 'never'.
}

Ok, seems I've understood the reason: earlier type of form[field] was string | number, but now it is string & number which is never. But I still ned to make it working...

Upvotes: 2

Views: 42

Answers (1)

Qwertiy
Qwertiy

Reputation: 21400

Seems like solved by using a generic parameter:

interface IData {
  a: string;
  b: number;
}

var form: IData = { a: "", b: 0 };

function doSmth<F extends keyof IData = keyof IData>(field: F, value: IData[F]) {
  form[field] = value;
}

doSmth("a", "abc")
doSmth("b", 13)

Upvotes: 1

Related Questions