繁体   English   中英

Typescript:根据接口键获取接口属性的类型

[英]Typescript: get type of interface property based on interface key

我正在构建一个 function 需要一次更新 object 的一个字段。 这个 object 是通过接口T定义的。

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

这应该是这个 function 的类型签名:

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

这会产生错误: '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我不是说typeof key ,因为typeof key可以是T的任何键,但是如果key = a等,我希望value属性为TypeA类型。

我怎样才能 select T的对应键值的类型?

您正在尝试使用实际值索引类型,这是不允许的。 您需要使用类型( 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'.

typescript 中的类型和实际值之间有明显的区别,因为类型信息在转译后丢失。 因此,您不能使用实际值来定义类型逻辑。 唯一的方法是提取真实值的类型值(例如,使用typeof ),这就是编译器建议将真实值转换为类型的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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