-
Notifications
You must be signed in to change notification settings - Fork 12.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Union inference works in only some cases #23312
Comments
If you have exactly one place where If you have more than one place where |
Ok, but in some cases a union type is being synthesized (the array and |
More specifically, we don't synthesize union types as part of inference. In any place where the call succeeds, the type let result: string | number
// Works
const fromArray = <Z>(cases: Z[]): Z => cases[0];
// The array literal has the type (string | number)[] - we didn't synthesize that during inference
result = fromArray(['a', 3]);
// Doesn't work
const fromTuple = <Z>(cases: [Z, Z]): Z => cases[0];
// Z gets two candidates: string, number
// The array literal's type is not observed during inference
result = fromTuple(['a', 3]);
// Doesn't work
const fromVarargs = <Z>(...cases: Z[]): Z => cases[0];
// Z gets two candidates: string, number
// The union type string | number doesn't exist anywhere
result = fromVarargs('a', 3);
// Works
const fromStringIndex = <Z>(cases: { [k: string]: Z }): Z => cases.x;
// The fresh object literal has an index signature to string|number
result = fromStringIndex({ x: 'a', y: 3 });
// Doesn't work
const fromRecord = <Z>(cases: { [K in 'x' | 'y']: Z }): Z => cases.x;
// Each property maps to a Z so we have two candidates: string, number
result = fromRecord({ x: 'a', y: 3 }); |
I see, thanks for the explanation! |
TypeScript Version: 2.8.1
Search Terms:
union inference
Code
Expected behavior:
All of these examples should work, with the type parameter
Z
being inferred as the union of the types of all values provided.Actual behavior:
Only the array and string index cases work.
Playground Link
The text was updated successfully, but these errors were encountered: