Skip to content

Generic template literal index does not resolve value typeΒ #50030

Open
@zachkirsch

Description

@zachkirsch

Bug Report

πŸ”Ž Search Terms

template string key generic "is not assignable to type"

πŸ•— Version & Regression Information

  • This changed between versions 4.6.4 and 4.7.4

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

// ObjectWithUnderscoredKeys creates an object where:
//   Keys are the strings in K, except each with an underscore prefix
//   Values are all `true`
export type ObjectWithUnderscoredKeys<K extends string> = {
    [k in K as `_${k}`]: true;
};

// it works without generics
function nonGenericTest(objectWithUnderscoredKeys: ObjectWithUnderscoredKeys<"foo" | "bar">, key: "foo" | "bar") {
  const shouldBeTrue: true = objectWithUnderscoredKeys[`_${key}`];
}

// but not with generics
function genericTest<K extends string>(objectWithUnderscoredKeys: ObjectWithUnderscoredKeys<K>, key: K) {
  // ERROR:
  // Type 'ObjectWithUnderscoredKeys<K>[`_${K}`]' is not assignable to type 'true'.
  //   Type 'ObjectWithUnderscoredKeys<K>[`_${string}`]' is not assignable to type 'true'.
  const shouldBeTrue: true = objectWithUnderscoredKeys[`_${key}`];
}

πŸ™ Actual behavior

In the generic function genericTest, indexing into the object doesn't yield a value with the type true.

πŸ™‚ Expected behavior

In the generic function genericTest, indexing into the object should yield a value with the type true.

Related issues

This seems similar to #48983, but that was marked as Working as intended and the behavior in this example doesn't seem like it should be intended.

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