Typescript从名称获取对象属性类型

时间:2019-11-21 12:18:38

标签: typescript typescript-typings typescript-generics

我正在尝试在反应式总线类中的打字稿中执行类型推断功能。

这里是一个例子:

  // 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”变量的类型是数字|字符串,但是我期望数字。

我想念什么吗?有可能吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

您对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中的一个特定键。