我正在尝试在反应式总线类中的打字稿中执行类型推断功能。
这里是一个例子:
// 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”变量的类型是数字|字符串,但是我期望数字。
我想念什么吗?有可能吗?
谢谢!
答案 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
中的一个特定键。