Repository navigation
Keyword to permit inferring a union for a type parameterΒ #44312
Description
Suggestion
π Search Terms
- Widen
- Generics
- Open
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
Right now TypeScript has some rules about when it decides to widen a generic type or not, which can produce confusing results for relatively similar function signatures:
declare function fn1<T>(items: Array<T>): T
declare function fn2<T>(items: Array<() => T>): T
declare function fn3<T>(items: Array<{ prop: T }>): T
let res1: number | string = fn1([42, "hi"])
let res2: number | string = fn2([() => 42, () => "hi"]) // string ("hi") is not a number
let res3: number | string = fn3([{ prop: 42 }, { prop: "hi" }]) // string ("hi") is not a numberRight now its entirely outside of your control what TypeScript will decide to do when a type parameter is not provided and what TypeScript does has changed a few times over the years.
It would help a lot if TypeScript gave you some more control over this behavior, to specify if you want your generics to widen or not.
Please ignore the syntax, just demonstrating where I'd expect it to go
// widen
declare function fn<widen T>(items: Array<() => T>): T;
fn([() => 1, () => 2, () => "three"]) // => number | string
// do not widen
declare function fn<donotwiden T>(items: Array<T>): T;
fn([1, 2, "three"]) // ERRπ Motivating Example
An increasingly popular way to use TypeScript is to produce types from runtime values, there are already lots of TypeScript features dedicated to making it easier to infer precise types from values, and there are even libraries like zod and io-ts to do things like:
let type = union(string(), number())
let value: unknown = ...
assert(value, type)
value // >> string | numberLibraries written in TypeScript are increasingly relying on TypeScript's value-to-type inference as part of their public API. So when TypeScript changes its rules about things like when to widen vs not widen, it can be much more dramatic of a breaking change that sometimes requires redesigning these libraries.
type Check<T> = (value: unknown) => value is T
function string(): Check<string> {...}
function number(): Check<number> {...}
function union<T>(...members: Assertion<T>[]): Check<T> {...}
let assert = union(string(), number()) // ERR: number is not a string
let assert = union<string | number>(string(), number())Right now there are a couple hacks you can do to trick TypeScript into having the desired widening behavior (by lying about the actual types). But there is no guarantee that this behavior will stick around between TypeScript versions.
π» Use Cases
type Check<T> = (value: unknown) => value is T
function string(): Check<string> {...}
function number(): Check<number> {...}
function union<widen T>(...members: Check<T>[]): Check<T> {...}
let assert1 = union(string(), number())
let assert2 = union<string | number>(string(), number())
type SomeUnionToStayInSyncWith = string | number
let assert3 = union<SomeUnionToStayInSyncWith>(string(), number())
Activity
whzx5byb commentedon May 28, 2021
See Distributive Conditional Types
And this will make your examples work.
Example1
Example2
jamiebuilds commentedon May 28, 2021
Sure but you've changed the signature of
union()'s type parameters. The point is that the type parameters are part of the public APIRyanCavanaugh commentedon May 28, 2021
Aside: For clarity, this isn't "widening" (that process is only about converting literal types to their corresponding primitives, and some others). I don't think we have a name for the particular process of deciding when it's OK / not OK to infer a union for a type argument in the presence of multiple candidates. But it's clear in context what you mean here.
For
nowiden, I'm not sure how to reason about the behavior being described here. Presumably all three of these lines either have an error or don't have an error, but it's IMO very difficult to make an argument thatnoWiden(arr1)should be an error, and nothing meaningful about the code should change when we inline that expression.There's a ton of subtlety here around the inference candidate collection process - while the examples in the OP look similar, from a type system perspective the inference algorithm sees very different things. I wouldn't defend it as unsurprising but AFAIK we haven't actually broken much about this in the past (counterexamples welcomed for my own learning).
I think the intuition here is something like "don't infer a union unless one of the inference candidates is a union"... but literally one of the inference candidates is a union in these cases. There'd have to be some stronger theoretical principle to rely on to make this work in a way that was at least somewhat consistent in the presence of refactoring an argument to a local.
widenis much clearer IMO. There's a step after candidate collection that roughly says, if we can't produce a unifying type except by making a union (in the absence of a constraint to say otherwise), then issue an error and fall back to the constraint type. That could trivially be made dependent on the type parameter declaration and everything would pretty much work from there.Some more real-world use cases would be useful to help consider.
jamiebuilds commentedon Jun 1, 2021
I didn't really have a use case for
nowidenanyways, I was making assumptions about how this process worked internally, so if that's nonsensical I'm happy to drop it.I guess you could rename
widentoprefer-unionfor the sake of discussion:Which operates like this:
There's actually a number of ways TypeScript already has the desired
prefer-unionbehavior:Then there are places where TypeScript is producing a union but possibly not ideal for
prefer-union:And finally places where TypeScript bails out instead of producing a union:
[-]Intentionally widen generics[/-][+]Keyword to permit inferring a union for a type parameter[/+]wardds commentedon Nov 11, 2022
This is our use case for inferring a union type. I didn't manage to work around having to manually declare the union type in the generic when calling our
isOneOftype guard. A new keyword seems like an elegant way to fix that, so you have my upvote.jamiebuilds commentedon Nov 17, 2022
Question: Which place makes more sense for TypeScript internally?
craigphicks commentedon Dec 17, 2023
If the definition for
oneOfis changed toit does not produce an error for
If instead you really wanted to constraint
aandbto be the same type (which you don't) then you need something else altogether, so there doesn't seem a use case where current behavior ofdeclare function oneOf<T,U>(a: T, b: T): Tis sound.As for this
oneOfexample, maybe the question should be, areand
intended to express the same semantics? (I think so).
Then why don't they behave the same?
The former is 4 character shorter.
Maybe it could be called a bug.
Here is another example of what seem to be semantically identical generics where one has trouble.