It appears to be an error. I believe it should have been specified as a string[]
.
Although the notation string[7]
is technically valid in TypeScript, it lacks practical meaning.
string
represents a primitive type. Due to JavaScript treating all values as objects, the string
type includes a range of allowed methods and indexed properties.
In vanilla JavaScript, "abs"[0]
yields a
. Given that TypeScript does not include a char
type, it must align with JavaScript behavior. Therefore, string[10000]
simply returns a
string
.
Below are the built-in properties of the string
type:
type StringProperties= {
[Prop in keyof string]: { key: Prop, value: string[Prop] }
}
https://i.sstatic.net/bL29D.png
How can we create a fixed-length string in TypeScript?
This can be achieved using conditional types. One method involves iterating over each character and placing them into an array. Subsequently, comparing the length of this array with the expected string length would provide clarity.
Consider the following example:
type ToArray<T extends string, Cache extends readonly string[] = []> =
T extends ''
? Cache
: T extends `${infer A}${infer Rest}`
? ToArray<Rest, [...Cache, A]>
: Cache
type IsValid<T extends string[], Len extends number> = T['length'] extends Len ? true : false
type IsLength<T extends string, Len extends number> = IsValid<ToArray<T>, Len> // ok
type Result1 = IsLength<'hello', 6> // false
type Result2 = IsLength<'hello', 5> // true
Playground
For insights into string validation techniques, check out my blog