microsoft / microsoft/TypeScript

Can't constrain a generic parameter to have string keys?

Open
#43,771 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: Index Types
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Bug Report

Search Terms: Type 'X' cannot be used to index type 'Y', constrain generic parameter to have string keys

  • This is the behavior in every version I tried
Code

Playground link

This type is meant to map another type's values to arrays of {message: V} but also allow {message:unknown} for other string keys.

type Example<M> =
  { [K in keyof M]?: {message: M[K]}[] } &
  { [key in string]: {message: unknown}[] };

For example, the intent is that Example<{ foo: string }> should become

{
  foo: {message: string}[];
  [key: string]: {message: unknown}[];
}

And this works: we know that "foo" and other strings are valid keys.

const obj: Example<{foo: string}> = {};
obj["foo"] = [{message: "hi"}];
obj["bar"] = [{message: "x"}];

But trying to use Example with a generic parameter gives errors. Even if we don't know M["foo"], we should know that keyof M is string.

// attempt to constrain M's keys to be strings
function test<M extends {[key in string]: unknown}>() {
  const obj: Example<M> = {};
  obj["foo"] = [];  // error: Type '"foo"' cannot be used to index type 'Example<M>'.
  obj["bar"] = [];  // error: Type '"foo"' cannot be used to index type 'Example<M>'.
}
// should fail, but doesn't -- we've tried to constrain M to have string keys
test<{ 4: string }>();
🙁 Actual behavior

Example<M> cannot be indexed using string when M is a generic parameter.

🙂 Expected behavior

It should always be possible to index with string, since the definition of Example includes { [key in string]: ... }.

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 the concrete Example<{ foo: string }> case with the generic test<M extends { [key in string]: unknown }>() case. Investigate generic indexed-access and key-constraint behavior; done when string indexing works for the generic Example while a numeric-key instantiation is rejected.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.