5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

js,esファイルをtsに置き換えるのにやったこと

Last updated at Posted at 2020-02-21

置き換える前の状況

  • js, es, tsファイルが混在
  • テストが書かれてないコードが存在
  • JSDocは書かれている(間違ってる箇所あり)

tsからesファイルを読み込むことは出来ないので、呼び出し先のファイルがesだと、呼び出し元ファイルもesで作らないといけない。
どこかのタイミングでesをjsに変更していればよかったのですが、ずるずるとesが増えている状況。

目的

  • 今より型安全にする
  • esファイルを駆逐する

やったこと

型定義ファイルを作成

呼び出し頻度の高いファイルにデコレーターが使われており、それに型を付けることができませんでした。
https://github.com/microsoft/TypeScript/issues/4881

仕方なく以下のように型定義ファイルを作成し、対応しました。

Xxx.d.ts
declare module "xxx/xxx/Xxx" {
    import { Test } from "test";

    export default class Xxx {
        static count() => number;
    }
}
test.ts
// 呼び出しクラスに型なくても
import Xxx from "xxx/xxx/Xxx";
// 型定義ファイルを作ったおかげて型が効く
Xxx.count();

(* as any)で対応する。

今回の目的は完全な型づけではなく、tsファイル化することだったので、
依存度が小さい(型付けで得られる効果が小さい)ファイル、かつ、型付けコストが高いものは(* as any)で対応しました。

@ts-ignoreする

(* as any)で対応できない場合や、型の解決に時間がかかる場合は@ts-ignoreで対処しました。

型がない弊害

型がないので関数のインターフェースが決めれず、以下のようなモンスターが生まれていました。

xxx.js
async function something(somethinId: number): Promise<any[] | null | object> {
  if (isHappened) {
    return [];
  }
  if (isSomething) {
    return null;
  }
  return {};
}

JSDocは書かれているものの、渡す引数の型を間違えている。(動いているの?:scream_cat:

xxx.js
export default class Test {
    /**
     * コンストラクタ
     * @param {string} name
     * @param {number} id
     */
    constructor(name, id) {
        this.name = name;
        this.id = id;
    }
}

const test = new Test(name, null);

その他にも、存在しない関数を呼び出してる等もありました。(実行されないだろう箇所に書いてあったので、問題はなかったです。)

型 >>>>>> コメント

以上です。

5
1
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?