简体   繁体   中英

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'? '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 ?

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 (eg, with typeof ), which is why the compiler suggests transitioning your real value into a type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM