Skip to content

Instantly share code, notes, and snippets.

@CHBaker
Created September 5, 2023 22:23
Show Gist options
  • Save CHBaker/22213410c5145a089e1d2789fe825eac to your computer and use it in GitHub Desktop.
Save CHBaker/22213410c5145a089e1d2789fe825eac to your computer and use it in GitHub Desktop.
Strong Typed Switch Functional
const executeIfFunction =
<Wrapped extends Unwrapped | (() => Unwrapped), Unwrapped>(f: Wrapped): Unwrapped =>
typeof f === 'function' ? f() : f;
const switchf =
<ValueType>(cases: { [key: PropertyKey]: ValueType }) =>
(defaultCase: ValueType) =>
(key: PropertyKey) =>
cases.hasOwnProperty(key) ? cases[key] : defaultCase;
export const switchCase =
<KeyType extends PropertyKey, ValueType>(cases: { [key in KeyType]?: ValueType }) =>
(defaultCase: ValueType) =>
(key: KeyType) =>
executeIfFunction<ValueType | (() => ValueType), ValueType>(switchf<ValueType>(cases)(defaultCase)(key));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment