FrontEnd/TypeScript

[TS] Cannot find module '' or its corresponding type declarations.ts(2307)

위그든씨 2023. 2. 26. 16:19

TS에서 특정 라이브러리를 사용할 때, dependencies에 설치해도 제목과 같은 에러가 나는 경우가 있다.

TS는 라이브러리 타입을 읽을 때, index.d.ts를 먼저 찾는다.

이 파일은 라이브러리마다 있을 수도, 없을 수도 있다.

대표적으로 axios 같은 경우 node_module 내부에 index.d.ts가 미리 정의되어 있어서 TS에서 자동으로 타입 추론 가능

그러나 없을 경우 개발자가 추가로 처리해줘야 함.  

  1. @types/xxx 설치
  2. 외부 라이브러리 type 만들기

1. @types/xxx 설치 

node_module 내부에 index.d.ts를 정의하지 않은 라이브러리는 @types/xxx 에서 따로 정의한 경우가 있다.

예를 들어 chart.js를 install 했다고 가정했을 시, 아래와 같은 에러가 뜸.

import * as Chart from "chart.js";

// Could not find a declaration file for module 'chart.js'. '/Users/kyounghwan/Desktop/source/learn-typescript/project/node_modules/chart.js/dist/Chart.js' implicitly has an 'any' type.
// Try `npm i --save-dev @types/chart.js` if it exists or add a new declaration (.d.ts) file containing `declare module 'chart.js';

에러가 하라는 대로 npm i --save-dev @types/chart.js를 설치해주면 완료됨.

2. 외부라이브러리 type 만들기 (@types/xxx 없을 때)

npm i --save-dev @types/임의라이브러리를 했는데 해당 라이브러리가 없을 때가 있음.

이럴 경우 개발자가 임의로 타입을 만들어줘야 함.

  • root 레벨에 types 폴더를 만들고 그 내부에 임의라이브러리이름으로 폴더를 만든다.
  • 임의라이브러리 이름은 chart.js로 가정.
  • 그 이후 index.d.ts를 만든다.
// index.d.ts

declare module "chart.js" {
  // interface MyChart {}
  // 이곳에 method, property interface를 명명합니다.
}

interface를 declare 했다면, TS가 이 파일을 읽게 하기 위해 path를 알려준다.

해당 작업은 tsconfig.json 에서 작업

{
  "compilerOptions": {
    // ...

    // 우리가 작성한 types 폴더를 타입체크하라고 알려줍니다.
    "typeRoots": ["./node_modules/@types", "types"]
  },
  // ...
}

 

참고: 노경환님 블로그