Last active
April 21, 2023 01:30
-
-
Save jim-toth/5fa102e780420aace5ce5747a5e1265e to your computer and use it in GitHub Desktop.
EVM Address TypeScript
This file contains hidden or 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
type LengthOfString< | |
S extends string, | |
Acc extends 0[] = [] | |
> = S extends `${string}${infer Rest}` | |
? LengthOfString<Rest, [...Acc, 0]> | |
: Acc['length'] | |
export type HexNumbers = | |
| '0' | |
| '1' | |
| '2' | |
| '3' | |
| '4' | |
| '5' | |
| '6' | |
| '7' | |
| '8' | |
| '9' | |
export type HexCharsLower = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | |
export type HexCharsUpper = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | |
export type HexLower = HexNumbers | HexCharsLower | |
export type HexUpper = HexNumbers | HexCharsUpper | |
export type Hex = HexNumbers | HexCharsLower | HexCharsUpper | |
export type HexString<S> = | |
S extends '' | |
? unknown | |
: S extends `${Hex}${infer Rest}` | |
? HexString<Rest> | |
: never | |
export type EvmAddress<S extends string> = | |
S extends '' | |
? unknown | |
: LengthOfString<S> extends 42 | |
? S extends `0x${infer Rest}` | |
? HexString<Rest> | |
: never | |
: never | |
declare function onlyEvmAddress<S extends string>( | |
address: S & EvmAddress<S> | |
): any | |
onlyEvmAddress('0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA') // no error | |
onlyEvmAddress('shitpost') // type error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment