LoginSignup
3
1

More than 1 year has passed since last update.

Typescriptでメソッドチェーン可能なオブジェクトを作る簡単なサンプル

Last updated at Posted at 2022-03-09

簡単なサンプル

const calc = {
  result: 0,
  add(x: number) {
    this.result += x;
    return this;
  },
};

calc.add(2).add(3); // 5

thisを返すといい感じにつなげられる。

初期値ありのサンプル

const calc = (init: number) => ({
  result: init,
  add(x: number) {
    this.result += x;
    return this;
  },
});

calc(10).add(2).add(3); // 15

初期値が必要な時の書き方。

クラスで書くサンプル

class Calc {
  constructor(private result: number = 0) {}
  public add(x: number) {
    this.result += x;
    return this;
  }
}

new Calc(10).add(2).add(3); // 15

privateなんかでアクセスコントロールできる。
使う時にnewするのが面倒なら、初期値受けとってインスタンスを返すファクトリを作ってもよい。

実際の利用

上記のように足し算するだけだと使い道はないが、一般的には連続的に値を処理したい場合などで使われる。

array
[...Array(100)].map((_, i) => i).filter((i) => i % 2).reduce((a, b) => a + b);
cypress
cy.get('.todo-list li').find('label').should('contain', 'todo A')
jquery
$('div').css('background-color', 'black').css('color', 'white').fadeOut(2000);
3
1
3

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