type-fest
Version:
A collection of essential TypeScript types
60 lines (46 loc) • 2.04 kB
TypeScript
import type {UnwrapBrandedPrimitive} from './unwrap-branded-primitive.d.ts';
import type {IfNotAnyOrNever} from './internal/type.d.ts';
import type {IsStringLiteral} from './is-string-literal.d.ts';
/**
Returns the length of the given string.
Note: Whether a supplementary Unicode character, such as an emoji, counts as one character or two depends on the TypeScript compiler. TypeScript 7 counts it as one, unlike `String#length`.
@example
```
import type {StringLength} from 'type-fest';
type A = StringLength<'abcde'>;
//=> 5
type B = StringLength<'abcde' | 'fgh'>;
//=> 3 | 5
```
For non-literal strings, the result is `number` because the length of a non-literal string can be any number.
@example
```
import type {StringLength} from 'type-fest';
type A = StringLength<string>;
//=> number
type B = StringLength<Uppercase<string>>;
//=> number
type C = StringLength<`${string}abc`>;
//=> number
```
@category String
@category Template literal
*/
export type StringLength<S extends string> = IfNotAnyOrNever<S, {
// Sentinels are handled here already, and plain strings do not need brand normalization.
ifNot: (S extends object ? UnwrapBrandedPrimitive<S> : S) extends infer Input extends string
? IsStringLiteral<Input> extends true
// The intersection preserves the counter's recursion budget and generic numeric result.
? StringLengthImplementation<Input> & number
: number
: never;
ifAny: number;
}>;
// The input is already a literal, so count ten characters at a time, then the remainder, without retaining them.
type StringLengthImplementation<Value extends string, Counter extends unknown[] = []> =
Value extends `${string}${string}${string}${string}${string}${string}${string}${string}${string}${string}${infer Rest}`
? StringLengthImplementation<Rest, [...Counter, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown]>
: Value extends `${string}${infer Rest}`
? StringLengthImplementation<Rest, [...Counter, unknown]>
: Counter['length'];
export {};