xwitch
replaces switch
statement with function call.
xwitch
is short for expression switch
.
yarn add xwitch
or
npm install xwitch
import xwitch from 'xwitch';
import {AdminIcon, UserIcon, AnonymousIcon} from './some-icon-path';
type UserType = 'admin' | 'normal' | 'anonymous';
const user: UserType = 'admin';
// icon is inferred as ReactElement | null
const icon = xwitch(user)
.case('admin', () => <AdminIcon />)
.case('normal', () => <UserIcon />)
.case('anonymous', () => <AnonymousIcon />)
.default(() => null);
TODO
switch
syntax in JavaScript has following disadvantage.
switch
is not expression but statement. So, Sometimes, You must declare variable aslet
even if the variable will never changed.case
statement does not create a block scope. that specification makes it difficult to name a variable used in statements associated with thatcase
.- if you forget
break
statement, that causes unexpected behaviors.