[에러일지] Props 넘겨줄때 type error | Type '{ type: string; }' is not assignable to type ~~

HYEJIN·2022년 11월 7일
0

에러일지

목록 보기
1/2

동그란 버튼이 재사용 되어있어서 이것을 컴포넌트화 해서 사용하려고 하기위해서
뒤로가기, 추가 , 닫기 버튼에 따라서 이미지가 달라져야함으로 type을 3가지로 주었다.

// type/weather.ts 
export type RoundButtonType = "back" | "add" | "close";
//components/round_button.tsx
import { RoundButtonType } from "../type/weather";

export default function RoundButton(kind: RoundButtonType) {
  return <button></button>;
}

해당버튼을 사용하려는 페이지에서 컴포넌트를 아래와 같이 호출했다.


문제해결

1)

const test: RoundButtonType = "add";

위와같이 타입을 지정한 후 type에 test 변수를 전달하도록 테스트를 해봤지만 여전히 똑같이 에러가났다. 이부분이 문제가 아니라 props가 객체인데 타입지정을 잘못한 것이 문제였다.

//components/round_button.tsx
export default function RoundButton(kind: RoundButtonType) {
}

RoundButtonType은 interface나 객체 type로 지정해준게 아니라,
union type으로 문자열에 값일 지정해줬다.

props에서는 객체로 전달되는데 이 부분이 문제였다.

props 안에있는 kind라는 key를 가진 값이 있다고 생각해보면,저렇게 지정해주면 안된다.

해결책 1)
type에 지정한 RoundButtonType은 그대로 두고
매개변수를 객체화 해주는 방법
RoundButton(type: { kind: RoundButtonType })

export default function RoundButton(type: { kind: RoundButtonType }) {
  return (
    <button className="rounded-full border p-3 shadow-md shadow-gray-800">
      {changeImg(type.kind)}
    </button>
  );
}

해결책 2)
타입을 객체로 변경하고,
추가로 버튼에 다른 props들을 받을 수도 있기 때문에 key를 추가

// type/weather.ts 

//변경전
export type RoundButtonType = "back" | "add" | "close";

//변경후
export type RoundButtonType = "back" | "add" | "close";
export interface RoundButtonProps {
  kind: RoundButtonType;
  [key: string]: any;
}

//-------------------------------------------

// components/round_button.tsx 일부
export default function RoundButton({ kind, ...rest }: RoundButtonProps) {
  return (
    <button className="rounded-full border p-3 shadow-md shadow-gray-800">
      {changeImg(kind)}
    </button>
  );
}

any를 쓰는것이 안좋은것을 알고있지만
우선 지금은 프롭스로 어떤것이 올지 정해져있지 않아서 any로 지정해두었다.

이후 프로젝트를 진행할 때,
prop-types 패키지를 적용해서 관리해보면 좋을것같다.

0개의 댓글