-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Strings do not have known keys associated with their indexes #41037
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I had an old PR for this: #19846 |
Oh, I must have not searched well enough, adding that to the "related issues," except now this looks like a duplicate :/ |
When would this be useful? |
Well, this can be broken up into two distinct parts: Bug: |
A question on Stack Overflow for which this property would be the most obvious and clearest solution: extracting the first character of a string literal. Can be done with type NthCharOf<S extends string, N extends number> =
string extends S ? string :
number extends S ? EachCharOf<S> :
S extends `${infer H}${infer T}`
? [N, 0] extends [0, N]
? H
: NthCharOf<T, Decrement<N>>
: undefined;
type EachCharOf<S extends string, A extends string = never> =
string extends S ? string :
S extends `${infer H}${infer T}`
? EachCharOf<T, A | H>
: never;
type Decrement<N extends number> =
TupleOfLengthN<N> extends [unknown, ...infer T] ? T['length'] : number;
type TupleOfLengthN<N extends number, T extends unknown[] = []> =
[N, T['length']] extends [T['length'], N] ? T :
TupleOfLengthN<N, [...N, unknown]>; |
TypeScript Version: Nightly
Code
Expected behavior:
TypeScript associated keys with values for string literals.
Actual behavior:
TypeScript gives all indexes into a string the type
string
.TypeScript allows out of bounds indexes into string literals.
Playground Link: https://www.typescriptlang.org/play?esModuleInterop=false&experimentalDecorators=false&emitDecoratorMetadata=false&ts=4.1.0-insiders.20201010#code/PTAEBcFMGdwLlAIirRBuCBPADpAJqAIbSgDukANhUSdgPbTQCWARhZKEwHagAqAygBpQAYzoBbbOygVMnceICu4Qmw6EuBANZc6pHoXCiJ2JuwhNxkAFBiusCDCMBeJCnCIax++DTXrIKDQABZ0ihQELByQAI6KTABuhOxcRuB0oAAUAE6QhHh0XLKgANqgAOTg5cLlkNUV0PWV5aAAugCU-nYO8BVVoK7uJQAMrX62hdB07AB0FHQA5pkuzq7N7RiBAGbJ0JDCduDZhNly6WTBhnz8oFEUTJAJMF2TRiKX2Qiw2dwLA46wEoAVjGL3s00gc0WyxwkDoW1EHwGqyQ31+iA2oG2u323iOJzOGVIlyMAlulAeT2g-gA3tZQAzvD0nP8ys0anUao0av1Wl5ur5-IymWkEM1-kNRn4AL5AA
Related Issues: #19846
Strings, especially string literals, ought to be comparable to an array of characters when indexed.
When accessing a string
"foo"
the type should be comparable to indexingreadonly [ 'f', 'o', 'o' ]
, especially considering that JavaScript strings are completely immutable.I doubt anyone would be against the lengths being known too, ex:
const length: 4 = "test".length;
The text was updated successfully, but these errors were encountered: