打字稿从名称中获取对象 属性 类型

Typescript get object property type from name

我正在尝试在反应式总线内的打字稿中执行类型推断函数 class。

这是一个例子:

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

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

谢谢!

您的 getValue 实施推断出 return 类型的 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的return类型是T[K],其中K被推断为keyof T中的一个特定键。