Osk*_*son 3 typescript reactjs higher-order-components
IFoo我正在尝试编写一个通用的 React 组件,它需要两种类型(或)之一的 propsIBar以及接受所选类型的 props 的组件。
为什么下面的不起作用?
import React from 'react';
interface IFoo {
x: string;
}
interface IBar {
x: number;
}
const foo: React.FunctionComponent<IFoo> = (props: IFoo) => {
console.log("hello from foo!");
return <div>foo</div>
};
const bar: React.FunctionComponent<IBar> = (props: IBar) => {
console.log("hello from bar!");
return <div>bar</div>
};
interface IProps<T> {
props: T[];
Component: React.FunctionComponent<T>;
}
class HigherOrderComponent<T extends IBar | IFoo> extends React.Component<IProps<T>> {
render() {
const { props, Component } = this.props;
return (<div>
{props.map(prop => <Component {...prop}/>)};
</div>)
}
}
Run Code Online (Sandbox Code Playgroud)
这将返回以下错误:
Type 'T' is not assignable to type 'IntrinsicAttributes & T & { children?: ReactNode; }'.
Type 'IFoo | IBar' is not assignable to type 'IntrinsicAttributes & T & { children?: ReactNode; }'.
Type 'IFoo' is not assignable to type 'IntrinsicAttributes & T & { children?: ReactNode; }'.
Type 'IFoo' is not assignable to type 'T'.
'IFoo' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'IFoo | IBar'.
Type 'T' is not assignable to type 'IntrinsicAttributes'.
Type 'IFoo | IBar' is not assignable to type 'IntrinsicAttributes'.
Type 'IFoo' has no properties in common with type 'IntrinsicAttributes'.(2322)
Run Code Online (Sandbox Code Playgroud)
快速修复是添加:
{props.map((prop: T & {}) => <Component {...prop}/>)};
Run Code Online (Sandbox Code Playgroud)
我认为问题在于扩展运算符和联合类型(如果只有一种类型,则可以正常工作)。我知道 TS 以前也遇到过这样的问题:(
希望这可以帮助 :)
| 归档时间: |
|
| 查看次数: |
2230 次 |
| 最近记录: |