microsoft / microsoft/TypeScript

Inconsistency involving discriminated union and flatMap

オープン
#63,776 コメント 4 件 リアクション 1 件 担当者 2 名 GitHub で見る

@RyanCavanaugh がすでに取り組んでいます。

2026年8月21日 から。

  • #3301 @copilot-swe-agent による — マージされずにクローズ
  • #63948 @copilot-swe-agent による — オープン
Experimentation Needed
主要言語
Go
スター
111k
フォーク
14.3k
平均マージ
2日 4時間
マージ済み PR(30日)
132

説明

The following code works in TS, but errors in Go:

export type InputOp = { op: "add" } | { op: "remove"; value?: Array<unknown> };
export type OutputOp = { op: "add" | "remove" };

export function f(operations: InputOp[]): OutputOp[] {
  return operations.flatMap((operation) => {
    if (operation.op === "remove" && operation.value) {
      return [].map(() => ({ op: "remove" }));
    } else {
      return [operation];
    }
  });
}

The error in Go is:

src/flatMap.ts:5:29 - error TS2345: Argument of type '(this: undefined, operation: InputOp) => { op: "remove"; }[] | InputOp[]' is not assignable to parameter of type '(this: undefined, value: InputOp, index: number, array: InputOp[]) => readonly { op: "remove"; }[] | { op: "remove"; }'.
  Type '{ op: "remove"; }[] | InputOp[]' is not assignable to type 'readonly { op: "remove"; }[] | { op: "remove"; }'.
    Type 'InputOp[]' is not assignable to type 'readonly { op: "remove"; }[] | { op: "remove"; }'.
      Type 'InputOp[]' is not assignable to type 'readonly { op: "remove"; }[]'.
        Type 'InputOp' is not assignable to type '{ op: "remove"; }'.
          Type '{ op: "add"; }' is not assignable to type '{ op: "remove"; }'.
            Types of property 'op' are incompatible.
              Type '"add"' is not assignable to type '"remove"'.

5   return operations.flatMap((operation) => {
                              ~~~~~~~~~~~~~~~~

The example is seemingly quite close to minimal: removing the && operation.value, replacing the first case with [{ op: "remove" }], removing either case, replacing flatMap with map, or adding more explicit annotations, all either make TS error or make Go pass. I guess there's some complicated interaction of how Go is inferring the type of the callback when narrowing? Or maybe those things all let the inference happen some other way that works better, avoiding the problematic case.

(This is simplified from some real code which is a bit more complex, of course it doesn't make sense as-is.)

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

評価

この issue はまだ評価されていません。

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。