How do I declare a string that is of a specific length using typescript?

Viewed 12456

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.

3 Answers

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

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

Related