Last active
February 13, 2025 06:07
-
-
Save Phryxia/6161fe461f705faebe1713b6a62c1fef to your computer and use it in GitHub Desktop.
리액트 컴포넌트와 타입스크립트 다형성에 대한 주저리
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Big = { x: string } | |
type Small = Big & { y: string } | |
// 잘못된 다형적 컴포넌트 | |
interface Props { | |
value: Big // Small도 Big이니까 넣어도 됨 | |
onReport(newValue: Big): void // 이 코드의 의도는 (newValue: Small) => void도 전달받는 걸 상정함 | |
} | |
function WrongPolymorphicComponent({ value, onChange }: Props) { | |
function modify(oldValue: Big) { | |
// 다형적이지 못함. y의 속성이 증발함. | |
// 하지만 타입은 문제가 없음 | |
onReport({ x: oldValue.x + ' wow!' }) | |
} | |
function create() { | |
onReport({ x: 'x' }) // y는? | |
} | |
} | |
// 사용처 | |
function ComponentUsingSmall() { | |
const [small, setSmall] = useState<Small>({ /* 생략 */ }) | |
return ( | |
<WrongPolymorphicComponent | |
value={small} | |
onReport={setSmall} // 에러 안남 | |
/> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
객체지향과의 질감적 차이
리액트 컴포넌트 프로그래밍을 함수형이라고 뭉개기엔 어폐가 있지만, 불변성과 행위를 주고받는다는 관점에서 함수형이라고 부르겠다.