LoginSignup
558
353

More than 5 years have passed since last update.

TypeScript で型定義ファイル( d.ts )がないときの対処法

Posted at

はじめに

例えば npm からインストールした foobarモジュールの型定義がないとき

import foobar from 'foobar'

のようにモジュールをインポートすると、

Could not find a declaration file for module 'foobar'.
Try npm install @types/foobar if it exists or add a new declaration (.d.ts) file containing declare module 'foobar';

とコンパイルエラーが発生します。

大まかに分けると3対処法があります。

  • @types からインストールする
  • 型定義ファイル( d.ts )を自作する
  • require でモジュール読み込み

1. @types からインストールする

型定義ファイルが提供されているか試します。
TypeScript コンパイラの指示通り @types からのインストールを試します。

# npm
npm install --save @types/foobar
# yarn
yarn add @types/foobar

無事インストール出来たら解決です。

もし型定義が提供されておらず、 error An unexpected error occurred: "https://registry.yarnpkg.com/@types%2ffoobar: Not found". と表示された場合、

  • 型定義ファイル( foobar.d.ts )を自分で実装

もしくは

  • require でモジュール読み込み

をします。

2. 型定義ファイル( d.ts )を自作する

src/@types ディレクトリを作成します。
foobar.d.ts@types 下に作成します。

tsconfig.jsontypeRoots のデフォルト設定が @types ディレクトリになっています。
※ 型定義ファイルの保存場所を変える場合、tsconfig.json を設定します。

{
  "compilerOptions": {
    "typeRoots" : [".d.tsを入れるディレクトリのパス"]
  }
}

型定義ファイル( .d.ts ) の実装についてはこちらが参考になりました。
TypeScript の型定義ファイルと仲良くなろう

3. require でモジュールを読み込む

型定義ファイル( d.ts )を書くのが面倒な時の対処法です。
require でモジュールを読み込みます。

const foobar = require('foobar')

暗黙的に any 型になるので、型定義ファイル d.ts が見つからないエラーは消えます。

ただし TSLint の設定によっては [tslint] require statement not part of an import statement (no-var-requires) という警告がでます。
// tslint:disable-next-line:no-var-requires とコメントで require('foobar') についてだけ警告を無効にします。

// tslint:disable-next-line:no-var-requires
const foobar = require('foobar')

この状態では foobarany 型になり、型チェックも賢い補完も行われません。
自分の使う API を型付けして置くと良さそうです。

interface IFooBar {
  bazMethod(qux: string): string;
  fuga(hoge: number): boolean
}
// tslint:disable-next-line:no-var-requires
const foobar = require('foobar') as IFooBar;

読んでいただきありがとうございました❗

558
353
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
558
353