Skip to content

Instantly share code, notes, and snippets.

@ryangoree
Last active April 29, 2024 22:53
Show Gist options
  • Save ryangoree/4d30ba9f3eedf0cfb9a227f02742ea06 to your computer and use it in GitHub Desktop.
Save ryangoree/4d30ba9f3eedf0cfb9a227f02742ea06 to your computer and use it in GitHub Desktop.
A utility type that converts a string of words into a map of values.
/**
* A utility type that returns a union of space-separated words in a string.
*
* @example
* ```ts
* type Foo = Words<'foo bar baz'>;
* // => 'foo' | 'bar' | 'baz'
*/
type Words<TString extends string> =
TString extends `${infer Word} ${infer Rest}` ? Word | Words<Rest> : TString;
/**
* A utility type that converts a string of words into a map of values.
*
* @example
* ```ts
* type Foo = WordMap<'foo bar baz', number>;
* // => { foo: number, bar: number, baz: number }
* ```
*/
type WordMap<TString extends string, TValues = any> = {
[K in Words<TString>]: TValues;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment