storybook argTypes 추론이 안되는 문제
argTypes는 왜 추론이 안되는 것일까요
실제로는 argsTypes의 키의 밸류 오브젝트에는 추론되는 타입외에도 control 키를 넣을 수 있습니다.
이렇게 control의 값을 적절히 설정하고 control 값에 따라 options를 설정하면?
실제 스토리북에서도 잘 반영되는 것을 볼 수 있습니다.
심지어 꽤 중요한 기능이에요 각 props이 받는 각각의 옵션을 문자열단위로 외우고 다니는 취미가 있지 않는 이상 굉장히 불편할테니까 이런 셀렉트 기능은 스토리북에서 거의 필수적이라고 봐도 무방합니다.
storybook ArgTypes
https://storybook.js.org/docs/api/arg-types
ArgTypes • Storybook docs
Storybook is a frontend workshop for building UI components and pages in isolation. Thousands of teams use it for UI development, testing, and documentation. It’s open source and free.
storybook.js.org
해당 링크에서 argTypes에 들어갈 수 있는 내용들을 설명해주고있습니다.
?? 아니 왜 이렇게 다 정리해뒀으면 이걸 자동완성되게는 안해두는거죠?
거기에다가 모든 옵션이 공통으로 처리되는게 아니라 특정 옵션은 조금 다르게 처리되는 경우도 존재합니다.
예를 들면 number의 경우는 다음과 같이 옵션을 줘야합니다.
{ control: { type: 'range', min: 1, max: 30, step: 3 } }
?? 왜 이런짓을..?
그래도 다행히 들어갈 수 있는 key와 들어가야하는 밸류가 위 문서처럼 정리가 되어있으니
타입으로 직접 만들어두면 쉽게 사용할 수 있을 듯 합니다.
type ArgGenerateParameter =
| {
control: 'object';
}
| {
control: 'check';
options: string[] | readonly string[];
}
| {
control: 'boolean';
}
| {
control: 'check';
options: string[] | readonly string[];
}
| {
control: 'inline-check';
options: string[] | readonly string[];
}
| {
control: 'radio';
options: string[] | readonly string[];
}
| {
control: 'inline-radio';
options: string[] | readonly string[];
}
| {
control: 'select';
options: string[] | readonly string[];
}
| {
control: 'multi-select';
options: string[] | readonly string[];
}
| {
control: 'number';
min: number;
max: number;
step: number;
}
| {
control: 'range';
min: number;
max: number;
step: number;
}
| {
control: 'color';
presetColors: string[] | readonly string[];
}
| {
control: 'date';
}
| {
control: 'text';
}
| {
control: 'file';
accept: string;
};
export const argTypes = (param: ArgGenerateParameter) => {
switch (param.control) {
case 'color':
return { control: { type: param.control, presetColors: param.presetColors } } as const;
case 'number':
return { control: { type: param.control, min: param.min, max: param.max, step: param.step } } as const;
case 'range':
return { control: { type: param.control, min: param.min, max: param.max, step: param.step } } as const;
case 'file':
return { control: { type: param.control, accept: param.accept } } as const;
default:
return param;
}
};
문서를 그대로 타입으로 옮긴 뒤 특별한 처리가 필요한 부분은 switch 문으로 처리하고
처리가 필요없는 부분은 default로 내뱉게 설정을 해주었습니다.
행복하게 자동완성이 되는 모습을 확인할 수 있습니다.
스토리북 버전이 올라가면서 스토리북 스펙도 변경될 여지가 있으니 그때그때 눈치 잘보고 쓰시기 바랍니다.
현재 제가 작업한 스토리북 버전 기준은 8.0.4라는 것을 밝힙니다.
마치며
스토리북은 왜 이런짓을 해둔걸까요?
뭔가 깊은 사연이 있어서 그런건지 궁금하기도 합니다.
이슈를 남길 수도 있겠지만 귀찮으니 생략하겠습니다.
아무튼 저는 만들어둔 유틸함수 쓰면 되니까요
읽어주셔서 감사합니다.