Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Type 'string' cannot be used to index type 'T'" when using generics

Tags:

typescript

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.

like image 309
Arad Avatar asked Apr 24 '26 12:04

Arad


1 Answers

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

like image 104
Dominik Chudy Avatar answered Apr 26 '26 01:04

Dominik Chudy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!