【发布时间】:2020-03-17 09:11:10
【问题描述】:
我正在尝试在响应式总线类中的 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'变量的类型是数字|字符串,但我期待数字。
我错过了什么吗?有可能吗?
谢谢!
【问题讨论】:
标签: typescript typescript-typings typescript-generics