microsoft / microsoft/TypeScript

Inconsistency involving discriminated union and flatMap

Aperta
#63,776 4 commenti 1 reazione 2 assegnatari Vedi su GitHub

@RyanCavanaugh ci sta già lavorando.

Dal 21/8/2026.

  • #3301 di @copilot-swe-agent — chiusa senza merge
  • #63948 di @copilot-swe-agent — aperta
Experimentation Needed
Lingua principale
Go
Stelle
111k
Fork
14.3k
Merge medio
2g 4h
PR unite (30g)
132

Descrizione

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.)

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.