microsoft / TypeScript

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

Switch type by generic enum #59149

Closed Howard-Lam-UnitedVanning closed 2 days ago

Howard-Lam-UnitedVanning commented 3 days ago

πŸ” Search Terms

switch conditional type

βœ… Viability Checklist

⭐ Suggestion

A new way to define a generic type based on what another generic type extends by switch rather than chaining ternary operator

πŸ“ƒ Motivating Example

Current implementation

enum ModelType {
    DateTime,
    Date,
    Period,
}
type DateType< T extends (ModelType | undefined) = undefined> = T extends ModelType.Period ? DatePeriod : T extends ModelType.Date ? DateOnly : DateTime;

Potential new implementation

type DateType<T> = T switch {
    ModelType.Period => DatePeriod,
    ModelType.Date => DateOnly,
    _ => DateTime,
}

One should also be able to do this with a list of strings

πŸ’» Use Cases

  1. What do you want to use this for? For enforcing input model value type based on an option value
  2. What shortcomings exist with current approaches? Long chain of ternary operators, hard to read
  3. What workarounds are you using in the meantime? Long chain of ternary operators
MartinJohns commented 3 days ago

Duplicate of #51375.

Howard-Lam-UnitedVanning commented 2 days ago

Closing duplicate