【问题标题】:Is there a way to dynamically pick a type from interface in typescript有没有办法从打字稿中的接口动态选择类型
【发布时间】:2020-12-01 03:19:08
【问题描述】:

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

例子:

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

【问题讨论】:

    标签: typescript types typescript-typings


    【解决方案1】:

    您可以为此使用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类型解析。

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 2020-09-28
      • 2021-11-05
      • 1970-01-01
      • 2020-02-02
      相关资源
      最近更新 更多