"implicit conditional type", "conditional type without extends", "infer outside conditional type", "infer in generic constraint", "conditional type sugar"
β Viability Checklist
[X] This wouldn't be a breaking change in existing TypeScript/JavaScript code
[X] This wouldn't change the runtime behavior of existing JavaScript code
[X] This could be implemented without emitting different JS based on the types of the expressions
[X] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
Currently it's not possible touse the infer keyword outside of the "extends type" in a conditional type. I'd like to propose allowing it in a type arg constraint position.
π Motivating Example
This seems like a perfectly valid thing to do
type FirstWord<T extends `${infer Result} ${string}`> = Result
but it is not alowed.
There is a workaround using a conditional type
type FirstWord<T extends `${string} ${string}`> = T extends `${infer Result} ${string}` ? Result : never;
but it feels weird having to type the same condition twice. Also, the false branch is provably never hit, which makes it feel more weird having to use the conditional type.
It would probably be easiest to implement if the proposed syntax was simple treated as a syntactic sugar for the conditional type above.
π» Use Cases
What do you want to use this for?
Irrefutable pattern matching in type space.
What shortcomings exist with current approaches?
Having to duplicate the same condition twice, worse readability.
What workarounds are you using in the meantime?
A conditional type
type FirstWord<T extends `${string} ${string}`> = T extends `${infer Result} ${string}` ? Result : never;
π Search Terms
"implicit conditional type", "conditional type without extends", "infer outside conditional type", "infer in generic constraint", "conditional type sugar"
β Viability Checklist
β Suggestion
Currently it's not possible touse the
infer
keyword outside of the "extends type" in a conditional type. I'd like to propose allowing it in a type arg constraint position.π Motivating Example
This seems like a perfectly valid thing to do
but it is not alowed.
There is a workaround using a conditional type
but it feels weird having to type the same condition twice. Also, the false branch is provably never hit, which makes it feel more weird having to use the conditional type.
It would probably be easiest to implement if the proposed syntax was simple treated as a syntactic sugar for the conditional type above.
π» Use Cases