Suggestion
Provide a way for a user defined template literal type to be a fixed length or limited length.
π Search Terms
Template Literal Type Length
β
Viability Checklist
My suggestion meets these guidelines:
β Suggestion
An intrinsic string manipulation type similar to Uppercase<StringType>, but that results in a fixed length string with provided substring union repeated n times.
type Hex = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '0' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F'
type HexHash = `0x${FixedLength<Hex, 64>}`
π Motivating Example
const hexHash = '0xbaadf00dbaadf00dbaadf00dbaadf00dbaadf00dbaadf00dbaadf00dbaadf00d'
const hexAddress = '0xbaadf00dbaadf00dbaadf00dbaadf00dbaadf00d'
declare function wantsHash(hash: `0x${string}`): void
declare function wantsAddress(address: `0x${string}`): void
wantsHash(hexHash) // ok
wantsHash(hexAddress) // should fail
wantsAddress(hexHash) // should fail
wantsAddress(hexAddress) // ok
π» Use Cases
A lot of the work I do deals with byte arrays that are passed around as strings (because they are often pulled directly out of a JSON payload). These usually have a well defined length and a consistent prefix. For example:
const hexHash = '0xbaadf00dbaadf00dbaadf00dbaadf00dbaadf00dbaadf00dbaadf00dbaadf00d'
const hexAddress = '0xbaadf00dbaadf00dbaadf00dbaadf00dbaadf00d'
I would like to be able to write functions that are constrained to accept only strings of a certain length, and ideally only made up of certain characters. Currently, the best I can do is type as 0x${string}, but this doesn't allow me to differentiate between a 20 byte hex string and a 32 byte hex string which are effectively different types in this context and are incompatible with each other.
Suggestion
Provide a way for a user defined template literal type to be a fixed length or limited length.
π Search Terms
Template Literal Type Length
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
An intrinsic string manipulation type similar to
Uppercase<StringType>, but that results in a fixed length string with provided substring union repeatedntimes.π Motivating Example
π» Use Cases
A lot of the work I do deals with byte arrays that are passed around as strings (because they are often pulled directly out of a JSON payload). These usually have a well defined length and a consistent prefix. For example:
I would like to be able to write functions that are constrained to accept only strings of a certain length, and ideally only made up of certain characters. Currently, the best I can do is type as
0x${string}, but this doesn't allow me to differentiate between a 20 byte hex string and a 32 byte hex string which are effectively different types in this context and are incompatible with each other.