3

I'm using generics in TypeScript (v4.5.4) and the following code throws an error:

function foo<T extends Record<string, boolean>>(obj: T, key: string) {
    obj[key] = true; // ERROR: Type 'string' cannot be used to index type 'T'
}

Playground link

This makes no sense to me whatsoever, it's even more nonsensical given the fact that the following actually works with no errors:

const key: string = '';
const obj: Record<string, boolean> = {};
obj[key] = true; // NO ERROR

While as far I'm concerned the first code snippet is effectively doing the exact same thing.

I would like to know why this happens, and also how I could rectify the problem in the first snippet.

1
  • specify parameter key as type keyof T will get rid of your current error, but it also leads to another one (Type 'boolean' is not assignable to type 'T[keyof T]'.(2322))... I would just cast true as T[keyof T], @jcalz explains this pretty well in another answer here. Commented Mar 18, 2022 at 7:00

1 Answer 1

1

As far as I know, this is a bug, which was discussed pretty deeply on GitHub. Here's the link: https://github.com/microsoft/TypeScript/issues/47357

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.