[ 공모전 ] Title Component ( CVA Type) 2/5

최문길·2024년 6월 20일
0

공모전

목록 보기
4/46

CVA의 helper인 VariantProps를 알게 되었고, 적용을 해보았는데..


문제가 발생


import { VariantProps, cva } from 'class-variance-authority';

type T_CVAProps = VariantProps<typeof style> // 추가                               
interface I_TitleProps {
  className?:string,
  text:string,
  level:T_CVAProps
}
//...생략

문제가 발생하였다. 원인을 뒤적여 보니 T_CVAProps 의 타입을 보면

type T_CVAProps = {
    level?: 1 | 2 | 3 | 4 | 5 | null | undefined;
}

객체이다.

  • props로 전달하는 level은 Tag 컴포넌트로 dynamic하게 사용되는데 객체형태로 props로 전달하는데 태그 자체가 불가능하고,

const style = cva('normal-case mb-7', {
  variants: {
    level: {
      1: 'text-5xl leading-[3rem] font-black mb-3.5 uppercase',
      2: 'text-4xl leading-[2.25rem] font-black mb-3.5 uppercase',
      3: 'text-3xl leading-[1.87rem] font-bold',
      4: 'text-2xl leading-[1.5rem] font-semibold',
      5: 'text-xl leading-[1.25rem] font-medium',
    },
  },
});
cn(style({ level,} ...)
  • 위의 코드에서 보면 level은 숫자만 들어가며 조건부로 css를 뱉어주는건데
    T_CVAProps가 객체 이므로 타입 error를 내뱉는 것이다.

해결(?)

따라서 객체와 객체를 연결시켜주는 extends로 확장 시켜주자

type T_CVAProps = VariantProps<typeof style>
/*
type T_CVAProps = {
    level?: 1 | 2 | 3 | 4 | 5 | null | undefined;
}
*/
                               
interface I_TitleProps extends T_CVAProps {
  className?: string;
  text: string;
}

이렇게 extends로 확장시켜주면 I_TitleProps 의 타입은

 I_TitleProps {
  className?: string;
  text: string;
  level?: 1 | 2 | 3 | 4 | 5 | null | undefined;
 }

위와 같은 타입으로 지정 된다.
그러나


또 다시 한번 더 에러가 내뱉게 되는데....

0개의 댓글

관련 채용 정보