有两个基本React组件:
子组件:
type SubComponentProps = {
subText: string;
} & DynamicProps;
type DynamicProps =
| {
prop1?: "one" | "two";
prop2?: "three" | "four";
}
| {
prop1?: "1" | "2";
prop2?: never;
};
function SubComponent({ subText, prop1, prop2 }: SubComponentProps) {
return <p>{subText}</p>;
}
主要成分:
type MainComponentProps = {
mainText: string;
} & Pick<SubComponentProps, "prop1" | "prop2">;
function MainComponent({ mainText, prop1, prop2 }: MainComponentProps) {
return (
<div>
<h1>{mainText}</h1>
<SubComponent subText="Text" prop1={prop1} prop2={prop2} /> // <-- Error here
</div>
);
}
我希望MainComponent
从SubComponent
“继承”DynamicProps
,以便prop1
和prop2
可以从根级别首先传递到MainComponent
,然后传递到SubComponent
。同时,prop1
和prop2
仍然需要是动态的,这意味着如果prop1
作为"one"
或"two"
传递,则prop2
应该可用。但是,如果prop1
作为"1"
或"2"
传递,则prop2
应该不可用。类似于以下内容:
<MainComponent mainText="Text" prop1="one" prop2="four" />; // <-- Should be allowed
<MainComponent mainText="Text" prop1="1" prop2="four" />; // <-- Should not be allowed
我尝试使用Pick
实用程序类型来选择prop1
和prop2
,但它没有按预期工作,因为我得到这个错误:
Type '{ subText: string; prop1: "one" | "two" | "1" | "2" | undefined; prop2: "three" | "four" | undefined; }' is not assignable to type 'IntrinsicAttributes & SubComponentProps'.
Type '{ subText: string; prop1: "one" | "two" | "1" | "2" | undefined; prop2: "three" | "four" | undefined; }' is not assignable to type '{ prop1?: "1" | "2" | undefined; prop2?: undefined; }'.
Types of property 'prop1' are incompatible.
Type '"one" | "two" | "1" | "2" | undefined' is not assignable to type '"1" | "2" | undefined'.
Type '"one"' is not assignable to type '"1" | "2" | undefined'.
我还尝试将DynamicProps
直接赋值给MainComponentProps
,但这并不能解决问题:
type MainComponentProps = {
mainText: string;
} & DynamicProps;
你能告诉我问题是什么以及如何实现所描述的行为吗?
1条答案
按热度按时间lyr7nygr1#
可以使用条件类型在SubComponentProps联合上进行分布
Playground