Description
openedon Oct 8, 2022
Suggestion
π Search Terms
infer, constraints, generic, extends
β 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
It would be nice if the infer T
wouldn't lose the source constraint. I've always wondered why this is lost and couldn't find any explanation behind this in the issues etc. @DanielRosenwasser has suggested here that it might be worth opening an issue about this.
Note that since 4.7 it is possible to add extends Constraints on infer Type Variables - the feature request here is different because the constraint is known upfront. Such extends
would still be useful with the proposed feature because it can be used to limit the number of conditional types both when the source constraint is completely unbound/unknown or when you simply want to match a subtype of the source constraint.
π Motivating Example
I've bumped into this on several occasions, even such a simple doesn't compile right now:
type Prefix<Prefix extends string, Input extends string> = `${Prefix}${Input}`;
type Test<T extends string[]> = T extends [infer Head, ...any[]]
? Prefix<"foo", Head> // Type 'Head' does not satisfy the constraint 'string'.(2344) This type parameter might need an `extends string` constraint.
: never;
π» Use Cases
It would allow us to skip a lot of error-prone repetition when working with the infer keyword.