使用通用 React 组件时,在 TS 3.2+ 中出现错误
When using generic React components, get error in TS 3.2+
这段代码在 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'
TypeScript 是正确的。考虑以下因素:
foo<{error: string, whatever: number}>(obj => `${obj.error} (${obj.whatever})`);
这在您的泛型约束下有效,因为 {error: string, whatever: number}
扩展了 {error: string}
。
但是您只使用 error
键调用它。几乎可以保证无效
这段代码在 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'
TypeScript 是正确的。考虑以下因素:
foo<{error: string, whatever: number}>(obj => `${obj.error} (${obj.whatever})`);
这在您的泛型约束下有效,因为 {error: string, whatever: number}
扩展了 {error: string}
。
但是您只使用 error
键调用它。几乎可以保证无效