2

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)

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Great! By the way, I put the ^? there because it's used as a label for types. See this playground
@LeoDog896 - Ah of course. I always put the computed type there for the answer but forget to remove it in the playground :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.