Home > OS >  How can I get the length of a string using TypeScript types?
How can I get the length of a string using TypeScript types?

Time:11-15

I'm trying to get the length of a string as a number:

type Length = LengthOfString<"hello">
//   ^? should be 5

I'm not sure where to begin on this. How can I accomplish this?

(I'm trying to learn more about typescript's type system -- I am not applying this to JS code)

CodePudding user response:

One way is to use a template literal string to split of each char of the string. We append some element to the tuple L for each char we can retrieve.

type LengthOfString<T extends string, L extends any[] = []> = 
  T extends `${string}${infer R}` 
    ? LengthOfString<R, [...L, string]>
    : L["length"]

When there are no more chars left, we return the length of L

Result:

type Length = LengthOfString<"hello">
//   ^? 5

Playground

  • Related