快速问题-假设我有一个这样的组件:
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>
}
如果我们不传递nameA,Typescript中有没有办法强制使用nameB?
写<Component nameA={""} nameB={"John"} />
感觉很糟糕,我不想把nameA变成nameA?: string
,因为我希望至少有一个道具能通过。
这是C的一个过于简单化的版本。提前打<3
是的,您可以使用联合类型:
interface Props1 {
nameA: string;
nameB?: string;
}
interface Props2 {
nameB: string;
}
type Props = Props1 | Props2
意思是,如果你通过了nameA
,nameB
是可选的。但如果你没有通过nameA
-nameB
是必需的。