microsoft / microsoft/TypeScript

Inconsistency involving discriminated union and flatMap

Ouverte
#63,776 4 commentaires 1 réaction 2 personnes assignées Voir sur GitHub

@RyanCavanaugh y travaille déjà.

Depuis le 21/8/2026.

  • #3301 par @copilot-swe-agent — fermée sans fusion
  • #63948 par @copilot-swe-agent — ouverte
Experimentation Needed
Langage dominant
Go
Étoiles
111k
Forks
14.3k
Merge moyen
2 j 4 h
PR mergées (30 j)
132

Description

The following code works in TS, but errors in Go:
```ts
export type InputOp = { op: "add" } | { op: "remove"; value?: Array };
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:
```ts
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.)

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Évaluation

Cette issue n'a pas encore été évaluée.

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.