【问题标题】:Type 'string | number' is not assignable to type 'never' in Typescript输入\'字符串 | number\' 不可分配给 Typescript 中的类型 \'never\'
【发布时间】:2022-12-06 22:07:01
【问题描述】:

当我写一些代码时,我遇到了一些这样的问题:


function getObjectKeys<T extends object>(object: T) {
    return Object.keys(object) as (keyof T)[]
}

const props = {
    propA: 100,
    propB: 'text'
}

const store = { ...props }

getObjectKeys(props).forEach((key) => {
    store[key] = props[key]
})

报告了一些错误:

const store: {
    propA: number;
    propB: string;
}
Type 'string | number' is not assignable to type 'never'.
  Type 'string' is not assignable to type 'never'.

当我这样写时:


getObjectKeys(props).forEach((key) => {
    if (key === 'propA') {
        store[key] = props[key]
    } else if (key === 'propB'){
        store[key] = props[key]
    } else {
        store[key] = props[key]
    }
})

它可以工作但不是很好。如何解决?

【问题讨论】:

    标签: typescript typescript-generics typescript-eslint


    【解决方案1】:

    您可以将商店定义为const store: Record&lt;string | number, any&gt; = { ...props }

    【讨论】:

      【解决方案2】:

      问题是store[key]props[key]的类型都是string | number,但是属性分别只有stringnumber,它们不允许两种类型的值。知道实际上 props[key] 将是 store[key] 的正确类型,但 TypeScript 不知道。

      对于您当前的类型,我认为您别无选择,只能使用 @ts-ignore 或类型断言 ((store as any)[key] = props[key];) 覆盖错误。

      【讨论】:

        【解决方案3】:

        你应该避免在 TS 中使用 extends object。它不推荐或理想的解决方案,而是使用Record&lt;..., ...&gt;

        目标对象 store 必须是 Record&lt;string, any&gt; 才能使您的代码正常工作,因为 TS 不知道将提前添加哪些属性。

        function getObjectKeys<T extends Record<string, any>>(object: T) {
            return Object.keys(object) as (keyof T)[]
        }
        
        const props = {
            propA: 100,
            propB: 'text'
        }
        
        const store: Record<string, any> = {}
        
        getObjectKeys(props).forEach((key) => {
            store[key] = props[key]
        })
        
        

        playground link

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-12
          • 1970-01-01
          • 1970-01-01
          • 2023-02-22
          相关资源
          最近更新 更多