reactjs 从React中的子组件属性选取动态联合类型

vi4fp9gy  于 2023-01-08  发布在  React
关注(0)|答案(1)|浏览(126)

有两个基本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>
  );
}

我希望MainComponentSubComponent“继承”DynamicProps,以便prop1prop2可以从根级别首先传递到MainComponent,然后传递到SubComponent。同时,prop1prop2仍然需要是动态的,这意味着如果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实用程序类型来选择prop1prop2,但它没有按预期工作,因为我得到这个错误:

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;

你能告诉我问题是什么以及如何实现所描述的行为吗?

lyr7nygr

lyr7nygr1#

可以使用条件类型在SubComponentProps联合上进行分布

type DistributePick<T, U extends keyof T> = T extends any ? Pick<T, U> : never;

type MainComponentProps = {
  mainText: string;
} & DistributePick<SubComponentProps, "prop1" | "prop2">;

Playground

相关问题