【问题标题】:Type { [x: string]: T[S]; } is not assignable to type 'Partial<T>'类型 { [x: 字符串]: T[S]; } 不可分配给类型 'Partial<T>'
【发布时间】:2021-10-04 00:33:06
【问题描述】:

我有这个代码部分,很简单:

interface A {
    z: string;
    y: number;
}

let newA = <T, S extends keyof T>(key: S, value: T[S]): Partial<T> => {
    return {[key]: value};
}

我看到一条错误消息: Type '{ [x: string]: T[S]; }' is not assignable to type 'Partial&lt;T&gt;'

我可以假设问题与{} 有关,它总是将key 映射为string

但即使使用显式类型表示应该是 string 我也没有结果

只有一个可行的解决方案是删除Partial&lt;T&gt;,但这不是一个好的解决方案

希望能得到一些专家级的typescript的回答,他可以描述这个问题的机制,并得到这种情况的解决方案

注意!该问题仅与一般情况有关。没有它,一切都会好起来的。

Typescript Playground with this code

【问题讨论】:

  • 这个函数怎么调用?
  • 没有电话。错误在类型级别。后来我想它会是这样的:`newA('z', '10')

标签: typescript typescript-typings typescript-generics


【解决方案1】:

您不需要使用部分。具有计算键的对象总是被推断为{[prop:string]:any infered type}

你可以重载你的函数来避免这种行为:

type Json =
    | null
    | string
    | number
    | boolean
    | Array<JSON>
    | {
        [prop: string]: Json
    }

function record<Key extends PropertyKey, Value extends Json>(key: Key, value: Value): Record<Key, Value>
function record<Key extends PropertyKey, Value extends Json>(key: Key, value: Value) {
    return { [key]: value };
}

const result = record('a', 42) // Record<"a", 42>

【讨论】:

    猜你喜欢
    • 2020-04-03
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 2016-07-31
    • 2022-11-11
    • 2022-11-11
    • 2017-12-29
    • 2019-01-31
    相关资源
    最近更新 更多