microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.48k stars 12.43k forks source link

Infer keyword in typearg constraint #59158

Closed MichalMarsalek closed 2 months ago

MichalMarsalek commented 3 months ago

πŸ” 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

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

  1. What do you want to use this for? Irrefutable pattern matching in type space.
  2. What shortcomings exist with current approaches? Having to duplicate the same condition twice, worse readability.
  3. What workarounds are you using in the meantime? A conditional type
    type FirstWord<T extends `${string} ${string}`> = T extends `${infer Result} ${string}` ? Result : never;
MartinJohns commented 3 months ago

Duplicate of #39736. Used search terms: infer constraint in:title

typescript-bot commented 2 months ago

This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.