Skip to content

Instantly share code, notes, and snippets.

@RobinBuschmann
Last active December 7, 2020 06:50
Show Gist options
  • Save RobinBuschmann/522967e724a6a3f179857b216be124ea to your computer and use it in GitHub Desktop.
Save RobinBuschmann/522967e724a6a3f179857b216be124ea to your computer and use it in GitHub Desktop.
// Implementation
// ---------------
interface Cases<V> {
[value: string]: Resolver<V>;
default: Resolver<V>;
}
type Resolver<V> = () => V;
const switchcase = <V extends any>(value: string | number, cases: Cases<V>): V =>
cases[value in cases ? value : 'default']();
// Usage
// ---------------
const determine = (user: any) => switchcase(user, {
elisa: () => 'mother',
nora: () => 'daugher',
robin: () => 'father',
default: () => 'who?',
});
const res = determine('elisa')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment