Created
October 12, 2023 12:24
-
-
Save bagaskarala/39c13d4c9b5bcf9c9f35d39d8a7d971e to your computer and use it in GitHub Desktop.
typescript generic snippet
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
// mapping | |
enum Words { | |
One = 'one', | |
Two = 'two', | |
Three = 'three', | |
} | |
enum Numbers { | |
One = 1, | |
Two = 2, | |
Three = 3, | |
} | |
type _WordToNumber<Object extends {[Word in Words]: Numbers}> = Object | |
type WordToNumber1 = _WordToNumber<{ | |
[Words.One]: Numbers.One, | |
[Words.Two]: Numbers.Two, | |
[Words.Three]:Numbers.Three | |
}> | |
type OneWordAsNumber = WordToNumber1[Words.One] | |
// validation | |
type DiceSides = 4 | 6 | 8 | 10 | 12 | 20 | |
type DiceString< | |
Count extends number, | |
Sides extends DiceSides, | |
> = `${Count}d${Sides}` | |
type TwoDFour = DiceString<2,4> | |
type DiceStringToDiceRoll<String extends string> = | |
String extends `${infer Count extends number}d${infer Sides extends DiceSides}` | |
? {count: Count; sides: Sides} | |
: never | |
type TwoDFourRoll = DiceStringToDiceRoll<'2d4'> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment