1
0

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.

TypeScriptで引数がないメソッドとあるメソッドをオーバーロードする方法

1
Last updated at Posted at 2020-02-14

TypeScriptで
引数がある場合はsetter(しつつthisを返したい)
引数がない場合はgetterという事がしたくて

調べたところ引数なしの場合は
引数をoptionalにしてオーバーロードするらしいんですが

ちょっと気持ち悪いなぁ
void型の引き数にしたらいけたりして?

と思ってやったらいけちゃったのでメモです。

class Hoge {

  width(v:number):this;
  width(v:void):number; // 引数の型をvoidにしたらいけた
  width(v:any):any {
    if(typeof v === 'number') {
      this._width = v;
      return this;
    } else {
      return this._width;
    }
  }
}

と思ってやったらいけるにはいけたんですが
コメントにてもっと素晴らしい方法を教えていただきました。
(もっと素晴らしいというか自分のやり方はわりとクソだなと思いつつある)

width(v: number): this;
width(): number;
width(...v: [] | [number]): this | number {
    // ...
}

rest parameters(...)を使って
可変長引数として引数を受け取って判定する方法

引数の数が異なる場合のオーバーロードはこの方法が好きかも
と思います。

しかし引数の数は同じだけど、型が異なる
というケースの場合はこの書き方は少し冗長かもしれないですね

できるかできないかで言えば
方法はいくつもあるとは思いますが
より良いものや最適解を求めていきたい。

1
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?