假设我有一个辅助函数,该函数返回带有一些常量的通用组件的包装器
function fooBar(ComponentVariant: ComponentVariantType) {
return (
<Foo>
<ComponentVariant>
<Bar />
</ComponentVariant>
</Foo>
);
}
其中ComponentVariantType
类似于type ComponentVariantType = FunctionalComponentA | FunctionalComponentB | FunctionalComponentC
。
现在我收到一个构建错误,提示:
FunctionalComponentA refers to a value, but is being used as a type here.
FunctionalComponentB refers to a value, but is being used as a type here.
FunctionalComponentC refers to a value, but is being used as a type here.
答案 0 :(得分:0)
FunctionalComponentA
是表示运行时函数的值。要获取此类值的类型,您需要使用typeof
类型运算符:
type ComponentVariantType = typeof FunctionalComponentA | typeof FunctionalComponentB | typeof FunctionalComponentC.
尽管取决于这些组件的定义方式,但在ComponentVariant
时传递的道具必须与所有组件兼容。
declare const FunctionalComponentA: React.FC<{ a: string }>
declare const FunctionalComponentB: React.FC<{ b: string }>
declare const FunctionalComponentC: React.FC<{ c: string }>
type ComponentVariantType = typeof FunctionalComponentA | typeof FunctionalComponentB | typeof FunctionalComponentC
function fooBar(ComponentVariant: ComponentVariantType) {
return (
<div>
<ComponentVariant a="" b="" c=""></ComponentVariant> /* Must have all props*/
</div>
);
}