【问题标题】:How to correct the error ts2590 other than disabling typescript?除了禁用打字稿外,如何更正错误 ts2590?
【发布时间】:2022-06-27 22:06:57
【问题描述】:

我目前正在尝试创建一个 React Hook,它返回一个带有一些属性的 CSS 样式对象。但是出现了错误,我不知道为什么,但我想是因为对象太复杂而无法评估,还是我完全错了?

错误信息

表达式产生的联合类型太复杂而无法表示。 ts(2590)

import React from 'react';

interface Test {
    color?: string;
    backgroundColor?: string;
    border?: string;
}

export const func = (prop: Test): React.CSSProperties => {
    const result: React.CSSProperties = {};

    for (const some in prop) {
        const key = some as keyof Test;
        result[key] = prop[key]; // Expression produces a union type that is too complex to represent. ts(2590)
    }

    return result;
};

如果Test接口只有一两个属性,不会出现问题。但是有3个或更多,就会有错误。尽管 react 应用程序运行正常,甚至应用时返回的结果也显示了正确的样式。这很烦人,我可以忽略,但我想了解为什么会发生这种情况,以及是否有办法解决它,而不是禁用该行的打字稿。

PS:该项目是使用 Vite 创建的,并在 React v18Typescript v4.6.3 上运行

【问题讨论】:

    标签: reactjs typescript react-typescript


    【解决方案1】:

    试试这个:

    interface Test {
      color?: string;
      backgroundColor?: string;
      border?: string;
    }
    
    type TestKey = keyof Test;
    
    export function func<T extends CSSProperties>(property: T): T {
      const result = {} as T;
    
      // eslint-disable-next-line guard-for-in
      for (const some in property) {
        const key = some as keyof T;
        result[key] = property[key];
      }
    
      return result;
    }

    据我了解,问题在于 Test 接口与 CSSProperties 的来源并不完全相同,尽管它看起来确实如此......通过创建一个通用函数,我能够强制这样做,因为我们能够将 Test 扩展为 CSSProperties

    【讨论】:

      猜你喜欢
      • 2016-08-12
      • 2021-08-01
      • 2019-12-24
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 2021-09-01
      相关资源
      最近更新 更多