[英]When using generic React components, get error in TS 3.2+
This code compiles just fine with TypeScript 3.1.x此代码与 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" />;
}
}
But if I compile it with TypeScript 3.2 or newer, I get但是如果我用 TypeScript 3.2 或更新版本编译它,我会得到
error TS2322: Type '{ error: string; }' is not assignable to type 'TErrorProps'.
Is this a regression in TS 3.2 or did 3.2 fix a loophole my code was taking advantage of?这是 TS 3.2 中的回归还是 3.2 修复了我的代码正在利用的漏洞?
Interestingly, this code fails to compile in 3.1 as well有趣的是,这段代码在 3.1 中也无法编译
interface IErrorProps {
error: string;
}
export default function foo<TErrorProps extends IErrorProps>(
ErrorCmp: (props: TErrorProps) => string
) {
return () => {
return ErrorCmp({ error: 'test error' });
}
}
with the error有错误
Argument of type '{ error: string; }' is not assignable to parameter of type 'TErrorProps'
TypeScript is correct.打字稿是正确的。 Consider the following:考虑以下:
foo<{error: string, whatever: number}>(obj => `${obj.error} (${obj.whatever})`);
This is valid under the constraints of your generic, as {error: string, whatever: number}
extends {error: string}
.这在您的泛型的约束下是有效的,因为{error: string, whatever: number}
extends {error: string}
。
But you are calling it with only the error
key.但是您只使用error
键调用它。 It is almost guaranteed to be invalid.它几乎可以肯定是无效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.