JavaScript/TypeScript
[TypeScript] props으로 받은 함수의 타입 지정하기
junvely
2022. 12. 1. 12:47
✨props으로 받은 함수의 타입 지정하기
타입스크립트를 아무것도 모른 상태로 처음 사용하면서, 타입을 지정하는데에 어려움이 있었다.
예를들어 다음과 같이 일반적으로 타입을 명확하게 지정하기 쉬운 string, number, boolean 등은
타입을 지정할 때 크게 고민이 필요하지 않았지만,
interface ICheckBoxProps {
label?: string;
placeholder: string;
type?: 'email' | 'password' | 'text' | 'number';
autoComplete?: string;
setValue: React.Dispatch<React.SetStateAction<string>>;
required?: boolean;
maxLength?: number;
inputRegexCheck?: ?
}
props으로 함수를 전달받는 경우, 또 함수가 특정 값을 리턴하지 않는 어떤 로직을 수행하는 함수라면
어떤 타입을 지정해야 하는지에 대해 어려움이 있었다.
하지만 고민한 것과 달리 생각보다 쉽게 답을 찾을 수 있었다.
.
.
그냥 해당 함수명에 마우스를 hover하면 너무나도 친절하게 타입을 안내해 준다...😂

위에서 친절하게 안내해준 타입을 가져와 지정해 준다.
interface ICheckBoxProps {
label?: string;
placeholder: string;
type?: 'email' | 'password' | 'text' | 'number';
autoComplete?: string;
setValue: React.Dispatch<React.SetStateAction<string>>;
required?: boolean;
maxLength?: number;
inputRegexCheck?: (event: React.KeyboardEvent<HTMLInputElement>) => void; // 타입 지정
}
=> void 는 리턴 값으로 아무것도 리턴하지 않는 함수라는 것을 의미한다.
타입스크립트는 처음 사용할 땐 멘붕의 연속이지만, 알고보면 참 친절한 언어인 것 같다..😅
<참고>
https://react.vlpt.us/using-typescript/02-ts-react-basic.html
728x90
반응형