【问题标题】:Typescript get object property type from nameTypescript 从名称中获取对象属性类型
【发布时间】:2020-03-17 09:11:10
【问题描述】:

我正在尝试在响应式总线类中的 typescript 中执行类型推断功能。

这是一个例子:

  // This is the function
  getValue<T>(data: T, key: keyof T) {
    return data[key];
  }

  // This is the test
  interface IState {
    field1: number;
    field2: string;
  }

  const state: IState = {
    field1: 123,
    field2: 'abc'
  };

  const x = getValue(state, 'field1');

成功推断出键变量(我不能键入与界面键不同的值)。 问题是这样做的'x'变量的类型是数字|字符串,但我期待数字。

我错过了什么吗?有可能吗?

谢谢!

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案1】:

    您的getValue 实现推断返回类型为T[keyof T],即number|string

    你想要的可以通过以下方式实现:

    function getValue<T, K extends keyof T>(data: T, key: K) {
      return data[key];
    }
    
    // This is the test
    interface IState {
      field1: number;
      field2: string;
    }
    
    const state: IState = {
      field1: 123,
      field2: 'abc'
    };
    
    const x = getValue(state, 'field1');
    

    这样,getValue 的返回类型为T[K],其中K 被推断为keyof T 中的一个特定键。

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 1970-01-01
      • 2020-02-28
      • 2021-07-07
      • 2017-04-25
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多