microsoft / microsoft/TypeScript
Inconsistency involving discriminated union and flatMap
@RyanCavanaugh 已经在做这个了。
开始于 2026年8月21日。
- 主要语言
- Go
- 星标
- 111k
- 派生
- 14.3k
- 平均合并
- 2 天 4 小时
- 30 天内合并 PR
- 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.)
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
评估
这个 Issue 还没有评估数据。