Skip to content

Support for switch statement shorthandΒ #61038

Closed as not planned
Closed as not planned
@Arctomachine

Description

@Arctomachine

πŸ” Search Terms

"switch shorthand"

βœ… Viability Checklist

⭐ 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    SuggestionAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it adds

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions