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

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);

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

  • https://twitter.com/trashh_dev/status/1558827043504078849
  • https://twitter.com/anuraghazru/status/1558836599269445637
  • https://twitter.com/CodingCarter/status/1558924142379950080

Tags:

Typescript