Skip to content

Instantly share code, notes, and snippets.

@jim-toth
Last active April 21, 2023 01:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jim-toth/5fa102e780420aace5ce5747a5e1265e to your computer and use it in GitHub Desktop.
Save jim-toth/5fa102e780420aace5ce5747a5e1265e to your computer and use it in GitHub Desktop.
EVM Address TypeScript
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