microsoft / microsoft/TypeScript

Strings do not have known keys associated with their indexes

Open
#41,037 5 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

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: https://github.com/microsoft/TypeScript/pull/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;

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked TypeScript Playground reproduction and compare string indexing with the readonly tuple example. The requested behavior is for literal string indexes to produce character literal types, reject out-of-bounds indexes, and potentially infer literal lengths; the issue names no source files or tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.