Search

Link to 타입 문제 해결하기

에러 문구

Type 'string | undefined' is not assignable to type 'To'. Type 'undefined' is not assignable to type 'To'.ts(2322) index.d.ts(98, 5): The expected type comes from property 'to' which is declared here on type 'IntrinsicAttributes & LinkProps & RefAttributes<HTMLAnchorElement> & { theme?: Theme | undefined; }'
Shell
복사

수정 전 코드

// 기존 소스 코드 const SettingButton: React.FC<ButtonProps> = ({ children, to }) => { return ( <StyledLink to={to}> <ButtonStyle>{children}</ButtonStyle> </StyledLink> ); }; // 기존 타입 코드 import { MouseEventHandler } from 'react'; interface ButtonProps { children: React.ReactNode; to?: string; onClick?: MouseEventHandler<HTMLDivElement>; } export default ButtonProps;
TypeScript
복사
Link 컴포넌트에서 to prop은 string 타입이거나 location 객체를 받는데, 타입스크립트는 to prop으로 undefined가 올 수 없다고 말하고 있다. 이는 ButtonProps 인터페이스에서 to가 옵셔널(string | undefined)로 선언되어 있기 때문에 발생하는 문제이다.

해결 방법

ButtonProps에서 to prop을 옵셔널이 아닌 필수로 만들거나, SettingButton 컴포넌트에서 to prop이 항상 정의되어 있는지 확인해야 한다.
// Button.type.ts export interface ButtonProps { children: React.ReactNode; to: string; // 'to' prop을 옵셔널이 아닌 필수로 변경 onClick?: MouseEventHandler<HTMLDivElement>; }
TypeScript
복사
SettingButton 컴포넌트 사용 시 to prop이 항상 정의되어 있어야 한다. 예를 들어, MainPage에서 SettingButton을 사용할 때 다음과 같이 수정할 수 있다.
// MainPage.tsx에서 SettingButton 컴포넌트 사용 예시 <SettingButton to='/setting'>참여자 설정</SettingButton>
JavaScript
복사
만약 to prop이 조건부로 전달되어야 한다면, to prop이 undefined일 경우를 처리하는 로직을 추가해야 한다. 예를 들어, SettingButton 컴포넌트 내부에서 to prop을 다룰 때 아래와 같이 처리할 수 있다. 이렇게 하면 to prop이 undefined일 때 오류를 발생시켜 개발자에게 알려주고, 이를 해결하기 위한 조치를 취할 수 있다.
// Button.tsx export const SettingButton: React.FC<ButtonProps> = ({ children, to }) => { if (to === undefined) { throw new Error('The "to" prop is required for the SettingButton component.'); } return ( <StyledLink to={to}> <ButtonStyle>{children}</ButtonStyle> </StyledLink> ); };
JavaScript
복사
// 기존 타입 코드 const SettingButton: React.FC<ButtonProps> = ({ children, to }) => { return ( <StyledLink to={to}> <ButtonStyle>{children}</ButtonStyle> </StyledLink> ); }; // 수정 타입 코드 import { MouseEventHandler } from 'react'; interface ButtonProps { children: React.ReactNode; to: string; onClick?: MouseEventHandler<HTMLDivElement>; } export default ButtonProps;
TypeScript
복사