網站搜尋

reactjs - 要求至少傳入一個 prop 給元件 [typescript]


快速問題——假設我有一個像這樣的元件:

interface ComponentInterface {
    nameA: string;
    nameB?: string;
}

const Component: React.FC<ComponentInterface> = (props) => {
     const { nameA, nameB } = props 
     const name = nameB || nameA;

     return <div>Hello World! Name: {name}</div>
}

在 Typescript 中,有沒有辦法在我們沒有傳入 nameA 時,使 nameB 成為必填項?

寫 <Component nameA={""} nameB={"John"} /> 感覺很糟糕,而我不想把 nameA 改成 nameA?: string,因為我希望至少傳入其中一個 prop。

這當然是一個過於簡化的版本。提前謝謝你!<3

答案#1

是的,你可以使用聯合類型:

interface Props1 {
    nameA: string;
    nameB?: string;
}

interface Props2 {
    nameB: string;
}

type Props = Props1 | Props2

這意味著,如果你傳入 nameA,nameB 是可選的。但如果你不傳入 nameA,則 nameB 是必需的。