import type / export type
| 対応: | TypeScript 3.8(2020) |
|---|
『import type』と『export type』は、型情報のみをインポート・エクスポートする構文です。実行時には完全に除去されるため、バンドルサイズの削減や、型だけを参照したい場合の依存関係の整理に役立ちます。
構文
// 型のみインポート
import type { TypeName } from './module';
import type DefaultType from './module';
// 型のみエクスポート
export type { TypeName };
export type { TypeName } from './module'; // 再エクスポート
// 通常のインポートに type を混在させる(TypeScript 4.5+)
import { someValue, type SomeType } from './module';
サンプルコード
// types.ts
export type User = {
id: number;
name: string;
};
export interface ApiResponse<T> {
data: T;
status: number;
}
export const BASE_URL = 'https://wp-p.info/sandbox/api.php'; // 値(型ではない)
// main.ts
import type { User, ApiResponse } from './types';
// import { BASE_URL } from './types'; // 値は import type では取得できない
import { BASE_URL } from './types'; // 値は通常の import を使う
async function fetchUser(id: number): Promise<User> {
const res = await fetch(`${BASE_URL}/users/${id}`);
const json: ApiResponse<User> = await res.json();
return json.data;
}
// TypeScript 4.5+ のインライン type 修飾子
import { readFile, type PathLike } from 'fs';
function read(path: PathLike): void {
readFile(path, 'utf-8', (err, data) => {
if (err) throw err;
console.log(data);
});
}
概要
TypeScript のコードはトランスパイル時に型情報が削除されます。しかし通常の『import』で型を読み込んだ場合、バンドラやトランスパイラによっては副作用のある import として残ることがあります。『import type』を使うと、型のみを利用していることが明示され、コンパイル後は確実に除去されます。
TypeScript 4.5 以降では、インポートリスト内の個別の識別子に『type』修飾子を付けるインライン形式も利用できます。これにより、値と型を1つの『import』文にまとめながら、型だけを明示できます。
『isolatedModules: true』(Babel・esbuild・SWC などを使う場合に推奨される設定)を有効にすると、型のみを再エクスポートする際に通常の export が使えなくなり、『export type』の使用が必須になります。
記事の間違いや著作権の侵害等ございましたらお手数ですがこちらまでご連絡頂ければ幸いです。