【发布时间】:2018-12-05 02:25:26
【问题描述】:
我正在尝试创建一个装饰器,其行为类似于 redux 的 connect 装饰器:在装饰组件中注入一些额外的道具。我的打字有问题
extra.d.ts
export interface ExtraProps {
extra: string;
}
// problem must be with this. Intent is to "add" the "extra" prop
// and not require it when the user actually renders it.
export function extra<P>(): (
Comp: ComponentType<P & ExtraProps>
) => ComponentType<P>;
sample.tsx
interface MyCompProps extends ExtraProps {
notSoExtra: string;
}
class MyComp extends React.Component<MyCompProps> {
render() {
console.log(this.props.extra, this.props.notSoExtra); // ok
return null;
}
}
// Decorating it here, prop types should be { notSoExtra: string }
const MyCompWithExtra = extra()(MyComp);
class App extends React.Component {
render() {
return <MyCompWithExtra notSoExtra="boring prop" />;
// error ^^^^^^
}
}
所以在渲染 MyCompWithExtra 时出现错误:
[ts] 类型 '{ notSoExtra: string; }' 没有共同的属性 类型'IntrinsicAttributes&{孩子?:ReactNode; }'。
当我像这样明确指定道具类型时:
const MyCompWithExtra = extra<MyCompProps>()(MyComp);
渲染时出现不同的错误
[ts] 类型 '{ notSoExtra: string; }' 不可分配给类型 'IntrinsicAttributes & MyCompProps & { children?: ReactNode; }'。
键入'{ notSoExtra:字符串; }' 不可分配给类型 '我的CompProps'。 '{ notSoExtra: string; 类型中缺少属性 'extra' }'。
如何以某种方式键入装饰器,以便在渲染装饰组件时可以省略道具?
【问题讨论】:
标签: reactjs typescript generics