Repository navigation
Support for switch statement shorthandΒ #61038
Description
Activity
It's not quite like a switch though, is it? In particular, all branches are executed because the whole object literal is evaluated before an individual property is plucked. So there's no narrowing Typescript can do here.
Reacted by Joe CalzarettaRight, if you want this to actually be a
switch-substitute then you need to use something likefunction h(u: U): number { const o = { a(u: A) { return u.a.value }, b(u: B) { return u.b.value } } return o[u.type](u); // error! }
which probably isn't "shorthand" anymore, and effectively reduces this feature request to #30581, the solution to which is #47109, refactor to generics like
interface TypeMap { a: { a: { value: number } }, b: { b: { value: number } } } type U<K extends keyof TypeMap = keyof TypeMap> = { [P in K]: { type: P } & TypeMap[P] }[K] function h<K extends keyof TypeMap>(u: U<K>): number { const o: { [P in keyof TypeMap]: (u: U<P>) => number } = { a(u) { return u.a.value }, b(u) { return u.b.value } } return o[u.type](u); // okay }
and that's not pretty or anything, so I could imagine wanting something more convenient if this pattern were widely used, and... well, this is the first I've seen of it.
RyanCavanaugh commented
on Jan 24, 2025 MemberMore actionsThis falls apart as a "switch" replacement as soon as the code gets even modestly more complex, e.g. this code always crashes:
const selectedListError = { fruit: testPlant.fruitList.slice(2), vegetable: testPlant.vegetableList.slice(1), berry: testPlant.berryList, }[testPlant.plantType];
I don't think it's worth adding a new kind of narrowing to support this
- addedSuggestionAn idea for TypeScriptAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it addsAn issue which adding support for may be too complex for the value it adds
on Jan 24, 2025 typescript-bot commented
on Jan 27, 2025 ContributorMore actionsThis issue has been marked as "Too Complex" and has seen no recent activity. It has been automatically closed for house-keeping purposes.
π Search Terms
"switch shorthand"
β Viability Checklist
β Suggestion
Support for type narrowing in
π 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:
π» Use Cases
Main use case: one line switch statement.
Two workarounds: normal switch or long ternary.