LoginSignup
7
3

More than 3 years have passed since last update.

typescript拡張関数

Last updated at Posted at 2020-11-30

概要

typescriptは良い言語ですがゴリゴリコードを書いていると、なんか物足りなくなってしまいます。
配列が空の場合にArray.lenght === 0や配列の重複要素を削除するのにArray.from(new Set([1,1,2,3]))など...

その際によく使いそうな処理をlibやutilityに切り出して使うのも良いのですが、typescriptには拡張関数という機能があるのでそれを使ってそれらを表現してみました。

設定方法

以下のような定義をして、使用したい場所でimportするだけ

test.extensions.ts
export {};

declare global {
  interface Array<T> {
    isEmpty(): boolean;
  }
}

Array.prototype.isEmpty = function () {
  return this.length === 0;
};
index.ts
import 'extensions/test.extensions.ts';

[].isEmpty()

使用例

  • 配列が空の場合
*.extensions.ts
Array.prototype.empty = function () {
  return this.length === 0;
};
*.ts
// before
[].lenght === 0
// after
[].isEmpty()
  • 配列の要素の重複を禁止
*.extensions.ts
Array.prototype.distinct = function () {
  return Array.from(new Set(this));
};
*.ts
// before
Array.from(new Set([1,1,2,3])) // [1,2,3]
// after
[1,1,2,3].distinct() // [1,2,3]
  • 配列の初めの要素を取得
*.extensions.ts
Array.prototype.front = function () {
  return this.length === 0 ? undefined : this[0];
};
*.ts
// before
[1,1,2,3][0]// 1
// after
[1,1,2,3].front() // 1

最後に

よく使う汎用的な処理を拡張関数として定義しておけば、vscodeなどで候補として表示されるので、割と便利でした。

続きまして、アルサーガパートナーズ Advent Calendar 2020 2日目の記事は @miumi さんの「エンジニア転職に必要な資金を調べてみた」です :tada:

7
3
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
7
3