> For the complete documentation index, see [llms.txt](https://toktokhan.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://toktokhan.gitbook.io/docs/basic-guides/convention/types/boilerplate/modules.md).

# modules

modules 폴더는 애플리케이션에서 사용하는 다양한 모듈에서 필요한 type을 지정한 곳입니다. \
\
init에는 declares(모듈 선언), react, react-query 모듈에 대한 타입 정의가 있습니다.<br>

[➡️](https://toktokhan.gitbook.io/docs/basic-guides/convention/types/boilerplate/modules#1.-declares) Declares&#x20;

[➡️](https://toktokhan.gitbook.io/docs/basic-guides/convention/types/boilerplate/modules#2.-react) React&#x20;

[➡️](https://toktokhan.gitbook.io/docs/basic-guides/convention/types/boilerplate/modules#3.-react-query) React-Query&#x20;

***

## 1. Declares

TypeScript에서 module로 직접 선언한 파일들이 있는 곳입니다. <br>

주로 외부 라이브러리나 프레임워크와 상호 작용하기 위한 타입 선언 파일들을 포함하는 모듈입니다. 이 모듈은 TypeScript로 작성된 외부 패키지의 타입 정보를 정의하여 코드 힌트와 유효성 검사를 개선하는 데 사용됩니다.

예를 들어 `.png`와 같은 이미지확장자는 일반적으로 타입 정보를 갖고 있지 않으므로 TypeScript가 해당 파일을 모듈로 인식하지 못하고 오류를 발생시킵니다.

```typescript
// ❌ Cannot find module '../../../public/images/new_og.png' 
// or its corresponding type declarations. ❌
import New from '../../../public/images/new_og.png';

```

하지만 `.png`확장자를 module로 선언 후&#x20;

```typescript
//image.d.ts
declare module '*.png';
```

TypeScript가 선언된 파일을 컴파일할 수 있도록 경로를 추가하면, TypeScript는 해당 파일들을 모듈로 취급하고 타입 검사를 진행하지 않습니다.

```json
// tsconfig.json
{
  // ...
  "include": ["next-env.d.ts", "app.d.ts", "**/*.ts", "**/*.tsx", "**/*.d.ts"],
  "exclude": ["node_modules", "./public/mockServiceWorker.js"]
}
```

{% hint style="info" %}
Tokplate에는 이미지 확장자들을 모듈로 선언하지 않았는데 왜 타입에러가 발생하지 않나요?\
\
next-env.d.ts에서 [`next/image-types/global`](https://github.com/vercel/next.js/blob/canary/packages/next/image-types/global.d.ts)을 참조하고 있기 때문입니다.&#x20;

```typescript
// next-env.d.ts
 <reference types="next/image-types/global" />
```

{% endhint %}

***

## 2. React

1. **PropsOf**\
   \
   타입 스크립트에서 컴포넌트의 프롭스 타입을 추출하는 유틸리티입니다. \
   \
   이 유틸리티를 사용하면 컴포넌트의 프롭스 타입을 추론하여 해당 프롭스를 다른 곳에서 사용할 수 있습니다.&#x20;

```typescript
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에서 사용되는 타입입니다. <br>

{% tabs %}
{% tab title="UseQueryParams" %}
useQuery 훅에서 사용됩니다.&#x20;
{% endtab %}

{% tab title="UseInfiniteQueryParams" %}
useInfiniteQuery 훅에서 사용됩니다.
{% endtab %}

{% tab title="UseMutationParams" %}
useMutation 훅에서 사용됩니다.
{% endtab %}

{% tab title="WrapVariables" %}
`variables` 을 필요로 하는 `UseQueryParams`와 `UseInfiniteQueryParams` 타입에서 사용됩니다. \
api 호출 시 필요한 `parameters`가 필수값인지, 옵셔널한 값인지에 따라 해당 형태의 타입을 리턴합니다.&#x20;
{% endtab %}
{% endtabs %}

{% hint style="info" %}
해당 섹션에서는 `UseQueryParams` Type에 대한 설명만 명시되어 있습니다. 해당 타입만 이해해도 다른 제네릭 타입들도 충분히 이해하실 수 있을 것 입니다.&#x20;
{% endhint %}

### UseQueryParams

**Tokplate** 에서는&#x20;

`react-query`의 `UseQueryOptions`와 `axios`의 `AxiosError`를 조합하여, `useQuery`를 더 편리하게 활용하기 위해 `useGetExampleListQuery`라는 커스텀 훅을 개발하여 사용하고 있습니다.

```markup
useQuery(key, function, options) 
          ↑      ↑         ↑
        쿼리키  api호출함수  쿼리옵션
```

api 호출 함수에서는 아래의 두 가지 매개변수가 필요합니다. 또한 각 매개변수에 대한 타입도 명시해 주어야 합니다.&#x20;

* **variables** \
  api 요청에 필요한 매개변수 (parameters)
* **options** \
  `useQuery`에서 제공하는 `options` \
  &#x20;e.g) `enabled`, `staleTime`, `onSuccess`, `onError`...

```typescript
 useQuery(
    queryKey,
    () => exampleApi.getList(params?.variables),
    params?.options, 
  );
```

\
`useQuery`를 활용하여 `useGetExampleListQuery` 라는 Custom Hook을 적용해보겠습니다.&#x20;

{% tabs %}
{% tab title="ExampleApi" %}
`ExampleApi` 의 `getList` 함수는 `GetExampleDto` type의 매개변수를 받아 `ExampleModel[]` 의 데이터를 리턴하는 `async function`입니다.&#x20;

```typescript
(property) ExampleApi.getList: (params?: GetExampleDto) => Promise<ExampleModel[]>
```

{% endtab %}

{% tab title="UseQueryParams 적용 전" %}
`UseQueryParams` type을 적용하기 전의 코드입니다. \
`react query` 를 용이하게 사용하기 위한 `Custom Hook` 에서 필요한 `variables` 와 `options`의 타입을 직접 명시해줘야 합니다.&#x20;

```typescript
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,
  );
}

```

{% endtab %}

{% tab title="UseQueryParams 적용 후 " %}
`exampleApi.getList(`) 함수의 타입을 제네릭으로 받아 해당 함수에서 적용된 타입이 명시됩니다.

```typescript
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,
  );
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
제네릭 타입을 활용하여 커스텀 훅의 타입 정의를 명확하게 표현하고, 이를 통해 유지보수성이 높은 코드를 구현할 수 있게 되었습니다.&#x20;

이 섹션에서 정의된 타입들은 보통 실무에서 직접 수정하거나 추가할 필요가 거의 없을 것입니다. 그러나 <mark style="background-color:green;">이러한 타입들을 이해하면 문제 대응이 신속해지며, 다른 부분에서도 유용하게 활용</mark>할 수 있으므로, 한 번 정확하게 이해하시고 계속해서 활용하시는 것을 권장합니다.
{% endhint %}

<br>

<br>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://toktokhan.gitbook.io/docs/basic-guides/convention/types/boilerplate/modules.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
