For example a string that can only be two characters long, which could be used for an ISO country code.
I have used Google and looked through the documentation but cannot find the answer.
For example a string that can only be two characters long, which could be used for an ISO country code.
I have used Google and looked through the documentation but cannot find the answer.
There isn't a way to specify a string length as a type.
If you have a finite list of country codes, you could write a string literal type:
type CountryCode = 'US' | 'CN' | 'CA' | ...(lots of others);
Actually it's possible to do
// tail-end recursive approach: returns the type itself to reuse stack of previous call
type LengthOfString<
S extends string,
Acc extends 0[] = []
> = S extends `${string}${infer $Rest}`
? LengthOfString<$Rest, [...Acc, 0]>
: Acc["length"];
type IsStringOfLength<S extends string, Length extends number> = LengthOfString<S> extends Length ? true : false
type ValidExample = IsStringOfLength<'json', 4>
type InvalidExapmple = IsStringOfLength<'xml', 4>
thanks to
You can achieve this using a type constructor and a phantom type which are some interesting techniques to learn about. You can see my answer to a similar question here