问题描述
正如标题所述,我试图根据我在函数中收到的键从接口动态获取类型。
示例:
interface State {
foo: boolean;
bar: string;
baz: number;
}
const globalState: State = {
foo: true,bar: 'somethin',baz: 42,}
const update = (key: keyof State,newValue: /* TYPE ME PLZ */): State => {
globalState[key] = newValue;
return globalState;
}
不幸的是,这会导致错误Type '<INSERTED_TYPE>' is not assignable to type 'never'
距离我最近的是State[keyof State]
,但它与我在函数中收到的键完全无关。
我的问题:是否可以获取newValue
参数的类型?
奖励问题:为什么错误消息never
中的类型是?
解决方法
您可以为此使用generics:
const update = <K extends keyof State>(key: K,newValue: State[K]): State => {
globalState[key] = newValue;
return globalState;
}
update('foo',true); // OK
update('foo',1); // Error: Argument of type '1' is not assignable to parameter of type 'boolean'
现在newValue
类型根据key
类型被解析。