LoginSignup
4
2

More than 3 years have passed since last update.

Typescriptで型定義(interface)のみのファイルをトランスパイルする

Posted at

何が起きたか?

  • とあるTypescriptとJavascriptの混在環境で,JavascriptからTypescriptをインポートするコードを書いた.
  • Typescriptがトランスパイルされて,Javascriptにされた後,JavascriptがTypescript(だったもの)のファイルをインポートする
  • また,Typescriptは型定義のみのTypescriptのファイルをインポートしている.

要は以下のような感じ

型定義ファイル

Types.ts
export {HogeType};

interface HogeType {
    x: number;
}

型定義をインポートして型を使う関数を書いたファイル

useType.ts
import {HogeType} from "Types"
export {getHogedData};

function getHogedData(): HogeType {
    let hogeData: HogeType;
    // do hoge
    return hogeData;
}

型定義をインポートした関数を使うjavascriptのファイル

useGetHogedData.js
import {getHogedData} from "useType";

function useGetHogedData() {
    const hoged = getHogedData();
}

さて,以上のコードはランタイムエラーとなる.

なぜか

Typescriptにおけるinterfaceやtypeはコンパイル時の型チェックのみに使用され,コンパイル後には無くなる.
単一のファイルに型のみを書くとファイルごと消える(?)そして,無いファイルをインポートしようとしているファイルも消える(なぜかは不明)
よって,実行時にはTypes.jsuseType.jsが消えて,useGetHogedData.jsはインポートエラーを吐いて終了する.

実は

以下の2つの書き方は結果が異なるようである.

interface1.ts
export {HogeType};

interface HogeType {
    x: number;
}
interface2.ts
export interface HogeType {
    x: number;
}

前者はファイル自体が生成されないが,後者はファイルだけ生成される(中身は'usestrict'のみ)
よって後者だとちゃんとランタイムエラーは起きず,動く.

不思議だ....

4
2
0

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
4
2