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

関数のユニオン型の値を可変長引数の関数型の変数に代入できてしまう

Last updated at Posted at 2025-09-14

はじめに

以下のコードには問題があります。

type F = (() => number ) | ((text: string) => number)
const f: F = (text) => text.length

type G = (...args: string[]) => number
const g: G = f

gを引数なしで呼び出したとき、実際にはfが引数なしで呼ばれ、ランタイムエラーとなるからです。

このコードでは型エラーが出ません(TS v5.9.2現在)。
期待する挙動としては、Gfを代入しようとしたら型エラーを起こすことでしょう。

関連するIssue

Geminiにmicrosoft/TypeScriptのissuesを調べさせたところ、以下が見つかりました。

既知だが未解決な問題に近いでしょうか。

おわりに

冒頭のようなあからさまな書き方をすることはないと思いますが、関数のユニオン型には気を付けなければならないと思います。

{BCB1E4D2-B842-4EE2-8F0C-CA7E6598B384}.png

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