首页 > 解决方案 > 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'变量的类型是数字|字符串,但我期待数字。

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

谢谢!

标签: typescripttypescript-typingstypescript-generics

解决方案


您的实现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');

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


推荐阅读