modules 폴더는 애플리케이션에서 사용하는 다양한 모듈에서 필요한 type을 지정한 곳입니다.
init에는 declares(모듈 선언), react, react-query 모듈에 대한 타입 정의가 있습니다.
Declares
React
React-Query
1. Declares
TypeScript에서 module로 직접 선언한 파일들이 있는 곳입니다.
주로 외부 라이브러리나 프레임워크와 상호 작용하기 위한 타입 선언 파일들을 포함하는 모듈입니다. 이 모듈은 TypeScript로 작성된 외부 패키지의 타입 정보를 정의하여 코드 힌트와 유효성 검사를 개선하는 데 사용됩니다.
예를 들어 .png
와 같은 이미지확장자는 일반적으로 타입 정보를 갖고 있지 않으므로 TypeScript가 해당 파일을 모듈로 인식하지 못하고 오류를 발생시킵니다.
Copy // ❌ Cannot find module '../../../public/images/new_og.png'
// or its corresponding type declarations. ❌
import New from '../../../public/images/new_og.png';
하지만 .png
확장자를 module로 선언 후
Copy //image.d.ts
declare module '*.png';
TypeScript가 선언된 파일을 컴파일할 수 있도록 경로를 추가하면, TypeScript는 해당 파일들을 모듈로 취급하고 타입 검사를 진행하지 않습니다.
Copy // tsconfig.json
{
// ...
"include": ["next-env.d.ts", "app.d.ts", "**/*.ts", "**/*.tsx", "**/*.d.ts"],
"exclude": ["node_modules", "./public/mockServiceWorker.js"]
}
2. React
PropsOf
타입 스크립트에서 컴포넌트의 프롭스 타입을 추출하는 유틸리티입니다.
이 유틸리티를 사용하면 컴포넌트의 프롭스 타입을 추론하여 해당 프롭스를 다른 곳에서 사용할 수 있습니다.
Copy type ButtonProps = { color: string; onClick: () => void; };
const Button:React.FC<ButtonProps> = (props) => { // ... };
type ButtonPropsExtracted = PropsOf<typeof Button>; // ButtonProps
3. React-Query
아래의 네 가지 제네릭 타입은 React Query
라이브러리를 사용하여 효율적으로 쿼리 기능을 구현하기 위해 사용되는 Custom hooks에서 사용되는 타입입니다.
UseQueryParams UseInfiniteQueryParams UseMutationParams WrapVariables
useInfiniteQuery 훅에서 사용됩니다.
variables
을 필요로 하는 UseQueryParams
와 UseInfiniteQueryParams
타입에서 사용됩니다.
api 호출 시 필요한 parameters
가 필수값인지, 옵셔널한 값인지에 따라 해당 형태의 타입을 리턴합니다.
UseQueryParams
Tokplate 에서는
react-query
의 UseQueryOptions
와 axios
의 AxiosError
를 조합하여, useQuery
를 더 편리하게 활용하기 위해 useGetExampleListQuery
라는 커스텀 훅을 개발하여 사용하고 있습니다.
Copy useQuery(key, function, options)
↑ ↑ ↑
쿼리키 api호출함수 쿼리옵션
api 호출 함수에서는 아래의 두 가지 매개변수가 필요합니다. 또한 각 매개변수에 대한 타입도 명시해 주어야 합니다.
variables
api 요청에 필요한 매개변수 (parameters)
options
useQuery
에서 제공하는 options
e.g) enabled
, staleTime
, onSuccess
, onError
...
Copy useQuery(
queryKey,
() => exampleApi.getList(params?.variables),
params?.options,
);
useQuery
를 활용하여 useGetExampleListQuery
라는 Custom Hook을 적용해보겠습니다.
ExampleApi UseQueryParams 적용 전 UseQueryParams 적용 후
ExampleApi
의 getList
함수는 GetExampleDto
type의 매개변수를 받아 ExampleModel[]
의 데이터를 리턴하는 async function
입니다.
Copy (property) ExampleApi.getList: (params?: GetExampleDto) => Promise<ExampleModel[]>
UseQueryParams
type을 적용하기 전의 코드입니다.
react query
를 용이하게 사용하기 위한 Custom Hook
에서 필요한 variables
와 options
의 타입을 직접 명시해줘야 합니다.
Copy export function useGetExampleListQuery<
TData = ExampleModel[],
TError = AxiosError<any>,
>(params: {
variables?: GetExampleDto;
options?: UseQueryOptions<ExampleModel[], TError, TData>;
}) {
const queryKey = EXAMPLE_API_QUERY_KEY.GET_LIST(params?.variables);
return useQuery<ExampleModel[], TError, TData>(
queryKey,
() => exampleApi.getList(params?.variables),
params?.options,
);
}
exampleApi.getList(
) 함수의 타입을 제네릭으로 받아 해당 함수에서 적용된 타입이 명시됩니다.
Copy export function useGetExampleListQuery(
params?: UseQueryParams<typeof exampleApi.getList>,
) {
const queryKey = EXAMPLE_API_QUERY_KEY.GET_LIST(params?.variables);
return useQuery(
queryKey,
() => exampleApi.getList(params?.variables),
params?.options,
);
}