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 3 years have passed since last update.

[TypeScript] 関数宣言/関数式オーバーロード

Posted at

2つの引数を同一型で受け取るような実装をしたい場合など、このように書くと良い

// 関数宣言
function add1 (v1: number, v2: number): number;
function add1 (v1: string, v2: string): string;
function add1 (v1: any, v2: any) {
  return v1 + v2;
}
console.log(add1(1, 2)); // 3
console.log(add1('A', 'B')); // AB
// console.log(add1('A', 2)); // ERROR

// 関数式
const add2: {
  (v1: number, v2: number): number;
  (v1: string, v2: string): string;
} = (v1: any, v2: any) => {
  return v1 + v2
}
console.log(add2(1, 2)); // 3
console.log(add2('A', 'B')); // AB
// console.log(add2('A', 2)); // ERROR

any を消して、(v1: string | number, v2: string | number) このように書くと

「演算子 '+' を型 'string | number' および 'string | number' に適用することはできません。ts(2365)」

というエラーがでて演算ができないエラーになる様子。

any消すのはなかなか難しい様子。

1
0
4

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?