【问题标题】:When using generic React components, get error in TS 3.2+使用通用 React 组件时,在 TS 3.2+ 中出现错误
【发布时间】:2019-09-20 09:10:58
【问题描述】:

这段代码使用 TypeScript 3.1.x 编译得很好

import React from 'react';

interface IErrorProps {
    error: string;
}

export default function foo<TErrorProps extends IErrorProps>(
    ErrorCmp: React.ComponentType<TErrorProps>
) {
    return () => {
        return <ErrorCmp error="test error" />;
    }
}

但如果我使用 TypeScript 3.2 或更高版本编译它,我会得到

 error TS2322: Type '{ error: string; }' is not assignable to type 'TErrorProps'.

这是 TS 3.2 中的回归还是 3.2 修复了我的代码正在利用的漏洞?

有趣的是,这段代码在 3.1 中也无法编译

interface IErrorProps {
    error: string;
}

export default function foo<TErrorProps extends IErrorProps>(
    ErrorCmp: (props: TErrorProps) => string
) {
    return () => {
        return ErrorCmp({ error: 'test error' });
    }
}

有错误

Argument of type '{ error: string; }' is not assignable to parameter of type 'TErrorProps'

【问题讨论】:

  • 我在 react-apollo 中使用 ts 3.2+ 编译时遇到错误,我认为这是同一个问题。这似乎是一个非常糟糕的变化,所以我很惊讶没有发现太多人点击它。

标签: reactjs typescript typescript3.0


【解决方案1】:

TypeScript 是正确的。考虑以下几点:

foo<{error: string, whatever: number}>(obj => `${obj.error} (${obj.whatever})`);

这在你的泛型约束下是有效的,因为{error: string, whatever: number} 扩展了{error: string}

但您只使用error 键调用它。几乎可以保证无效。

【讨论】:

  • 确实有道理,似乎 TS 3.2 基本上修复了这里的一个错误。谢谢!
猜你喜欢
  • 2020-04-03
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
  • 2016-02-11
  • 2021-05-26
  • 2019-02-16
  • 1970-01-01
  • 2018-07-29
相关资源
最近更新 更多