打字稿从名称获取对象属性类型 [英] Typescript get object property type from name

查看:37
本文介绍了打字稿从名称获取对象属性类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to do a type inference function in typescript inside a reactive bus 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'变量的类型是数字|字符串,但我期待数字.

Key variable is infered succesfully (i cannot type different values than interface keys). The problem is that doing this the type of 'x' variable is number|string but i'm expecting number.

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

Am i missing something? Is it possible?

谢谢!

推荐答案

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

Your implementation of getValue has inferred return type of T[keyof T], which is number|string.

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

What you want can be achieved the following way:

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.

This way, the return type of getValue is T[K], where K is inferred to be one specific key in keyof T.

这篇关于打字稿从名称获取对象属性类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆