簡體   English   中英

當組件是聯合類型時如何定義類型

[英]how to define type when the component is a union type

我有一個案例: https://codesandbox.io/s/stupefied-herschel-9lvmb?file=/src/App.tsx

import * as React from "react";
import "./styles.css";

const A: React.FC<{ a: string }> = ({ a }) => {
  return <div>{a}</div>;
};

const B: React.FC<{ a: string; c: number }> = ({ a, c }) => {
  return <div>{a + c}</div>;
};

const switchFunc = (num: number) => {
  // Maybe there are lots of cases with different returns(different components)
  if (num > 0.5) {
    return A;
  } else {
    return B;
  }
};

export default function App() {
  const condition = Math.random();

  const renderContent = (props: { a: string } | { a: string; c: number }) => {
    const Component = switchFunc(condition);

    return (
      <div>
        {/** omit other content */}
        {/** here type error!!! */}
        <Component {...props} />
      </div>
    );
  };

  return (
    <div className="App">
      {renderContent(condition > 0.5 ? { a: "hello" } : { a: "hi", c: 1 })}
    </div>
  );
}

但是我在使用<Component />時遇到了類型錯誤,那么在這種情況下我應該如何定義類型呢?

我不知道switchFunc返回的組件類型。 (在實際使用中,可能很多情況),所以它保持聯合類型,但props是交集類型。

謝謝

您已將A的道具定義為{ a: string }類型,而您可以將其傳遞給{ a: string; c: number }類型的道具。 { a: string; c: number } (反之亦然B )。

為了保持一致性,我將分別定義道具的類型,然后將其用作AB的道具類型:

type MyProps = { a: string } | { a: string, c: number };

const A: React.FC<MyProps> = (props: MyProps) => {
  const { a } = props; 
  return <div>{a}</div>;
};

const B: React.FC<MyProps> = (props: MyProps) => {
  const { a, c } = props;
  return <div>{a + c}</div>;
};

(話雖如此,我同意@Dilshan的觀點,即這不是理想的模式,也不是理想的變量名稱)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM