https://velog.io/@dongkyun/TS-useRef%EC%9D%98-%EC%97%AC%EB%9F%AC%EA%B0%80%EC%A7%80-%ED%83%80%EC%9E%85
이전에 작성해둔useRef의 타입에 대한 글을 읽고 오는 것이 이해하기 더 좋다.
HTML 태그의 속성에 대한 타입을 정의하는 방법은 크게 3가지이다.
type A1 = React.ComponentProps<'input'>;
type A2 = React.ComponentPropsWithRef<'input'>;
type A3 = React.ComponentPropsWithoutRef<'input'>;
DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>을 사용하는 경우도 있는데, 이는 ComponentProps<'input'>의 결과물과 동일하다.
(짧은 ComponentProps<'input'>을 쓰는 것이 더 좋지 않겠는가?)
3가지 방식을 지켜보다 한가지 의문이 생겼다.
ComponentProps와 ComponentPropsWithRef 모두 ref를 포함하는데 무슨 차이지?
const a1: A1 = {
ref: 'sss' // 정상
};
// LegacyRef
// const a1: DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>
const a2: A2 = {
ref: 'sss' // 에러!!!
};
// RefObject
// Omit<DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, "ref"> & {
// ref: ((instance: HTMLInputElement | null) => void) | React.RefObject<HTMLInputElement> | null | undefined
// }
const a3: A3;
// Omit<DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, "ref">
실제로 찍어보면 ref의 타입이 LegacyRef와 RefObject로 다르다는 것을 알 수 있다.
https://zerodice0.tistory.com/244
LegacyRef에 대한 내용은 이곳에 나와있다.
과거 class 문법을 사용했을 때는 ref값으로 string이 들어갈 수 있었다고한다. 이를 만족시키기 위한 타입이 LegacyRef인 것으로 보인다. 보통 class 문법을 사용하지 않기 때문에 LegacyRef가 아닌 RefObject로 타입이 추론되도록 하는 것이 더 정확해보인다.
동균님은 무슨 속성이세요?