Skip to content

Carry over source constraints to the inferred type parameterΒ #51108

Open

Description

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Experimentation NeededSomeone needs to try this out to see what happensSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions