Closed as not planned
Description
π Search Terms
"switch shorthand"
β Viability Checklist
- 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 isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β Suggestion
Support for type narrowing in
const result = {
1: checkThis.one
2: checkThis.two
} [checkThis.number] || checkThis.more
π Motivating Example
Imagine you need to narrow type of object from 2 possible options and access property based on that type. Easy solution - ternary.
Now another option is added. Easy solution - extend ternary by another check.
And few more options are added. Extending ternary any more will make it hard to read. Switch statement is easier to read, but it requires to declare variable first and then assign something to it based on condition.
But shorthand switch exists, similar to ternary. And it is not working with typescript.
Playground link or as code:
type Fruits = {
plantType: "fruit";
fruitList: string[];
};
type Vegetables = {
plantType: "vegetable";
vegetableList: string[];
};
type Berries = {
plantType: "berry";
berryList: string[];
};
type Plants = Fruits | Vegetables | Berries;
const testPlant = {
plantType: "fruit",
fruitList: [],
} as unknown as Plants;
const selectedListError = {
fruit: testPlant.fruitList,
vegetable: testPlant.vegetableList,
berry: testPlant.berryList,
}[testPlant.plantType];
const selectedListWorks =
testPlant.plantType === "fruit"
? testPlant.fruitList
: testPlant.plantType === "vegetable"
? testPlant.vegetableList
: testPlant.berryList;
Property 'fruitList' does not exist on type 'Plants'.
Property 'fruitList' does not exist on type 'Vegetables'.
Property 'vegetableList' does not exist on type 'Plants'.
Property 'vegetableList' does not exist on type 'Fruits'.
Property 'berryList' does not exist on type 'Plants'.
Property 'berryList' does not exist on type 'Fruits'.
π» Use Cases
Main use case: one line switch statement.
Two workarounds: normal switch or long ternary.