Type alias Strlen<S, Arr>

Strlen<S, Arr>: S extends `${infer L}${infer R}`
    ? Strlen<R, [...Arr, L]>
    : Arr["length"]

Get the length of a given string

Type Parameters

  • S extends string
  • Arr extends any[] = EmptyArray

Example

Strlen<'foo'>; // Result: 3

Can be used to create type constraints on string lengths:

// Only allow strings of length 8-10 characters
type ValidPassword<T extends string> = Strlen<T> extends 8 | 9 | 10 ? T : never;

// Function that only accepts valid password strings
function checkValidPassword<T extends string>(val: T & ValidPassword<T>) {
console.log(val);
}

// Works with string literals
const validPass = checkValidPassword('password123' as const); // OK
const invalidPass = checkValidPassword('short' as const); // Type error