일부 소품을 다른 반응 하위 구성 요소로 전달하는 반응 구성 요소를 사용할 때 일부 유형 정의를 하위 구성 요소에 이미 정의 된 부모에 다시 작성하는 것을 발견했습니다.
interface ParentProps {
onChange: (value: string) => void; // I end up rewriting this, when it was already written on ChildProps interface.
}
const Parent: React.FC<ParentProps> = ({ onChange }) => {
return <Child onChange={onChange} label="Label 1" />;
};
// Child component. Could be imported from a third party library.
interface ChildProps {
onChange: (value: string) => void;
label: string;
}
const Child: React.FC<ChildProps> = ({ onChange }) => {
return <MyComponent onChange={onChange} />;
};
유형 정의 재 작성을 방지하는 기술이 있습니까?
얼마나 ChildProps
재사용 하려는지에 따라 다릅니다.
몇 가지 속성 만 재사용하려면 인덱싱 된 유형 쿼리에서 사용하여 특정 속성의 유형을 가져올 수 있습니다.
interface ParentProps {
onChange: ChildProps['onChange']
}
또는 모든 속성을 재사용하려는 경우 ParentProps
확장하도록 정의 할 수 ChildProps
있습니다.
interface ParentProps extends ChildProps {
}
또는 다음을 사용하여 하위 집합 만 선택할 수 있습니다 Pick
.
interface ParentProps extends Pick<ChildProps, 'onChange'> { // Pick<ChildProps, 'onChange' | 'label'> to pick more
}
또는 하위 집합을 제외한 모든 항목을 선택하려면 다음을 사용할 수 있습니다. Omit
interface ParentProps extends Omit<ChildProps, 'label'> { // Omit<ChildProps, 'onChange' | 'label'> to omit more
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다