구성 요소 [typescript] [duplicate]에 전달하려면 하나 이상의 prop이 필요합니다.
Nov 18 2020
빠른 질문-다음과 같은 구성 요소가 있다고 가정 해 보겠습니다.
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
싶지 않습니다.
이것은 ofc의 지나치게 단순화 된 버전입니다. 미리 타이! <3
답변
4 captain-yossarian Nov 18 2020 at 19:29
예, 유니온 유형을 사용할 수 있습니다.
interface Props1 {
nameA: string;
nameB?: string;
}
interface Props2 {
nameB: string;
}
type Props = Props1 | Props2
통과 nameA
하면 nameB
선택 사항입니다. 당신이 통과하지 않는 경우 그러나 nameA
- nameB
이 필요합니다.