8

The TypeScript team has been doing great work on string literal typing in recent updates (4.1 & 4.2). I am wondering if there is a way to type a fixed length string.

Ex.

type LambdaServicePrefix = 'my-application-service';
type LambdaFunctionIdentifier = 'dark-matter-upgrader';
type LambdaFunctionName = `${LambdaServicePrefix}-${LambdaFunctionIdentifier}`; // error: longer than 32 characters...

How I imagine it would go is something like, Array<64, string>;. TypeScript has the Tuple type so as an array I could fix length of an array. [string, ... string * 62, string].

type FutureLambdaIdType = `${LambdaServicePrefix}-${string[32]}`;
7
  • 2
    Oof, I'm guessing this would be easy enough if TS didn't have such shallow recursion limits. Everything I'm trying peters out well before you get to length 64 strings. Maybe I can brute force it but it will be uuuuugly
    – jcalz
    Feb 15, 2021 at 17:26
  • 1
    Right now the closest I can get is this. Interested in having that written up or are you holding out hope for something different?
    – jcalz
    Feb 15, 2021 at 17:40
  • I appreciate the effort on your example, hopefully they'll add this functionality to TypeScript someday, I think I will just manually confirm the length, AWS yells at you at runtime. I assumed it was not possible to achieve what I wanted, but hoped there might be a solution. @jcalz Do you know if your infer solution could throw an error if the string was too long? Feb 15, 2021 at 21:13
  • There's no "invalid type" or "throw types" as requested by microsoft/TypeScript#23689, so I can't write something that will just cause a compiler error if a string type is longer than 32 characters. But if we are allowed to do things with values you can get errors, like this. Does that work for you? If so I'll write it up, although you seem to have accepted a different answer already.
    – jcalz
    Feb 16, 2021 at 1:29
  • 1
    Also, you might want to go to microsoft/TypeScript#41160 to describe your use case, since they are trying to figure out if and how much people actually need regex-validated string types
    – jcalz
    Feb 16, 2021 at 1:32

4 Answers 4

13

UPDATED to reflect better recursive conditional type support

There are still, as of TS 4.7, no regular-expression-validated string types in TypeScript. Template literal types handle some, but not all, of the use cases for such regex types. If you have a situation like this where template literal types are insufficient, you might want to go to microsoft/TypeScript#41160 and describe your use case. The idea of a "string whose maximum length is N characters" for some N extends number would be easy enough to express with regex types, but is not easily achievable with template literals.

Still, let's see how close we can get.


A major roadblock stands in the way. TypeScript cannot easily represent the set of all strings less than N characters as a specific type StringsOfLengthUpTo<N>. Conceptually any given StringsOfLengthUpTo<N> is a large union, but since the compiler balks at unions with more than ~10,000 members, you can only describe strings of up to a few characters this way. Assuming you want to support the 95 characters of 7-bit printable ASCII, you will be able to represent StringsOfLengthUpTo<0>, StringsOfLengthUpTo<1>, and even StringsOfLengthUpTo<2>. But StringsOfLengthUpTo<3> would exceed the compiler's capacity, since it would be a union of over 800,000 members. So we have to give up on specific types.


Instead we can think of our type as a constraint used with generics. We need a type like TruncateTo<T, N> which takes a type T extends string and an N extends number and returns T truncated to N characters. Then we can constrain T extends TruncateTo<T, N> and the compiler would automatically warn on too-long strings.

It used to be that shallow recursion limits would prevent us from writing TruncateTo<T, N> for N greater than about 20 or so, but TypeScript 4.5 introduced support for tail recursion elimination on conditional types. That means we can write TruncateTo<T, N> by adding some extra accumulator arguments like this:

type TruncateTo<T extends string, N extends number,
    L extends any[] = [], A extends string = ""> =
    N extends L['length'] ? A :
    T extends `${infer F}${infer R}` ? (
        TruncateTo<R, N, [0, ...L], `${A}${F}`>
    ) :
    A

This works by having an A accumulator to store the string we're building up, and an L arraylike accumulator that keeps track of how long that A string is (string literal types don't have a strongly typed length property, see ms/TS#34692 for the relevant request). We build up A one character at a time until we either run out of the original string, or until we reach a length of N. Let's see it in action:

type Fifteen = TruncateTo<"12345678901234567890", 15>;
// type Fifteen = "123456789012345"

type TwentyFive = TruncateTo<"123456789012345678901234567", 25>;
// type TwentyFive = "1234567890123456789012345"

We can't directly write T extends TruncateTo<T, N> as TypeScript complains that this is a circular constraint. But we can at least write a helper function like this:

const atMostN = <T extends string, N extends number>(
    num: N, str: T extends TruncateTo<T, N> ? T : TruncateTo<T, N>
) => str;

and then you could call atMostN(32, "someStringLiteral") and it would either succeed or warn based on the the length of the string literal argument. Note that the str input is of a weird conditional type, whose sole purpose is to avoid the circular constraint. T is inferred from str, and then checked against TruncateTo<T, N>. If it succeeds, great. Otherwise, we give str the type of TruncateTo<T, N>, and we'll see an error message. It works like this:

const okay = atMostN(32, "ThisStringIs28CharactersLong"); // okay
type Okay = typeof okay; // "ThisStringIs28CharactersLong"

const bad = atMostN(32, "ThisStringHasALengthOf34Characters"); // error!
// -------------------> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// '"ThisStringHasALengthOf34Characters"' is not assignable to parameter of type 
// '"ThisStringHasALengthOf34Characte"'.
type Bad = typeof bad; // "ThisStringHasALengthOf34Characte"

Is it worth it? Maybe. The original answer here had to do some unsavory things to get even a fixed-length check. The current one isn't so bad, but it's still a bunch of effort to get a compile-time check. So you might still have a use case for regex-validated string types.

Playground link to code

2
  • Thanks for the incredible work, I commented on that issue, in my head it doesn't feel like it should be that hard to define a certain length for a string since it is just a sequence of characters and we already have tuple types which are fixed length arrays essentially. Feb 16, 2021 at 14:24
  • Sure, but there’s no built in “split” or “join” for string literal and tuple types, and if you build them yourself you hit recursion and/or union limits pretty quickly. String literals also don’t have a strongly typed length property, so there’s no easy handle to turn here.
    – jcalz
    Feb 16, 2021 at 14:31
5

There is no way to represent fixed-length strings with Typescript. There is a very upvoted proposal here, but still this feature has not been released.

If the length is very little, there are some workarounds suchs as the following:

type Char = 'a'|'b'|'c'|'d'|'e'|'f'|'g'|'h'|'i'|'j'|'k'|'l'|'m'|'n'|'o'|'p'|'q'|'r'|'s'|'t'|'u'|'v'|'w'|'x'|'y'|'z'
type String3 = `${Char}${Char}${Char}`
const a: String3 = 'aa'    // error
const b: String3 = 'bbbbb' // error
const c: String3 = 'ccc'   // OK
const d: String3 = 'abc'   // OK

But you can't handle big lengths since you will run into a "Expression produces a union type that is too complex to represent" error.

0
1

It is impossible to limit the length of string by typing or typescript utils.

You can, however, use regex to validate the string (including length):

/^([a-zA-Z0-9_-]){1,64}$/

1
type IsThirteen<T extends number> = 13 extends T ? true : never
type IsFifteen<T extends number> = 15 extends T ? true : never

type LengthOfString<S extends string, T extends string[] = []> = S extends `${string}${infer R}`
  ? LengthOfString<R, [...T, string]>
  : T['length'];

type IsLengthThirteenOrFifteen<T extends string> = true extends IsThirteen<LengthOfString<T>>
    ? T
    : true extends IsFifteen<LengthOfString<T>>
        ? T
        : never

function IsLengthThirteenOrFifteenGuard <T extends string>(a: IsLengthThirteenOrFifteen<T>) {
  return a;
}

const b = IsLengthThirteenOrFifteenGuard('1131111111111')

Sources:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.