Last active
April 29, 2024 22:53
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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