【问题标题】:Typescript: get type of interface property based on interface keyTypescript:根据接口键获取接口属性的类型
【发布时间】:2021-06-28 20:18:07
【问题描述】:

我正在构建一个需要一次更新对象的一个​​字段的函数。 这个对象是通过一个接口T定义的。

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

这应该是这个函数的类型签名:

(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'?。 IMO 我不是说typeof key,因为typeof key 将是T 的任何键,但我希望value 属性的类型为TypeA,如果key = a 等。

如何选择T对应键值的类型?

【问题讨论】:

    标签: javascript typescript strong-typing


    【解决方案1】:

    您正在尝试使用实际值索引类型,这是不允许的。您需要使用类型 (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),这就是编译器建议将真实值转换为类型的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-18
      • 2020-02-28
      • 2023-03-10
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多