Skip to content

Strings do not have known keys associated with their indexes #41037

Open
@ghost

Description

TypeScript Version: Nightly

Code

{
    const t: 't' = ("test" as const)[0];
}
{
    const t: 't' = ([ 't', 'e', 's', 't' ] as const)[0];
}

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 indexing readonly [ '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;

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions