首页 > 解决方案 > 有没有办法从打字稿中的接口动态选择类型

问题描述

正如标题所说,我试图根据我在函数中收到的键从接口动态获取类型。

例子:

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

标签: typescripttypestypescript-typings

解决方案


您可以为此使用泛型:

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类型解析的。

操场


推荐阅读