Skip to content
Advertisement

Typescript: get type of interface property based on interface key

I’m building a function that needs to update one field of an object at a time. this object is defined through an interface T.

interface T {
  a: TypeA;
  b: TypeB;
  c: TypeC;
}

This should be the type signature of this function:

(key: keyof T, value: typeof T[key]) => void

This generates the error: 'key' refers to a value, but it is being used as a type here. Did you mean 'typeof key'?. IMO I did not mean typeof key, since typeof key would be any key of T, but I want the value attribute to be of type TypeA if key = a, etc.

How can I select the type of the corresponding key value of T?

Advertisement

Answer

You are trying to index a type with a real value, and this is not allowed. You need to access it with a type (playground):

interface T {
  a: number;
  b: string;
  c: boolean;
}

const func = <K extends keyof T>(key: K, value: T[K]) => {};

func("a", 5);
func("b", 5); // Argument of type 'number' is not assignable to parameter of type 'string'.

There is a clear distinction between types and real values in typescript since the type information is lost after transpilation. Thus you cannot use real values to define type logic. The only way would be to extract the type value of a real value (e.g., with typeof), which is why the compiler suggests transitioning your real value into a type.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement