typescript-go icon indicating copy to clipboard operation
typescript-go copied to clipboard

Discrepancy inferring widened string type from context

Open benjaminjkraft opened this issue 4 months ago • 0 comments

Given this code:

declare function compact<T>(array: ArrayLike<T>): T[];
type MyEnum = "a" | "b" | "c";
const myArray = ["a", "b"] as const;
export function f() {
  const _: MyEnum[] = compact([...myArray, "c"]);
}

TS passes but Go gives:

src/compact2.ts:5:9 - error TS2322: Type 'string[]' is not assignable to type 'MyEnum[]'.
  Type 'string' is not assignable to type 'MyEnum'.

5   const _: MyEnum[] = compact([...myArray, "c"]);

i.e. it's inferring the type of the value "c" as string in this context, rather than the type "c" -- which then doesn't typecheck once we get up to the variable declaration.

Possibly the same root cause as #1016, but the details are a bit different (e.g. this one requires the ArrayLike, not just Array).

benjaminjkraft avatar Jun 02 '25 21:06 benjaminjkraft