Open
Description
Search Terms
suggestion infer extends type parameter constraint
Suggestion
Allow infer T
in the right of extends
of a type
statement.
Examples
This suggestion allows following code:
type ReturnType<T extends (...args: any) => infer R> = R;
Which behaves similarly as:
// this code is taken from lib.es5.d.ts
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
Use Cases
As demonstrated in the example, we sometimes use conditional types with the sole purpose of use of infer T
.
We have to repeat some piece of code if we want to constraint what types can be passed to ReturnType
.
So this suggestion provides an abbreviated syntax for this use case.
Open questions:
- Should union distribution occur for the new syntax?
My opinion is yes to align with existing conditional types- hmm, but then just replacing
any
withinfer _
would change the behavior...
- Should function type parameters also allow
infer T
?- No strong opinion
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, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.