我在 TypeScript (v4.5.4) 中使用泛型,但以下代码会引发错误:
function foo<T extends Record<string, boolean>>(obj: T, key: string) {
obj[key] = true; // ERROR: Type 'string' cannot be used to index type 'T'
}
这对我来说毫无意义,考虑到以下事实实际上没有错误,这就更加荒谬了:
const key: string = '';
const obj: Record<string, boolean> = {};
obj[key] = true; // NO ERROR
虽然我认为第一个代码片段实际上在做完全相同的事情。
我想知道为什么会发生这种情况,以及如何解决第一个片段中的问题。
最佳答案
据我所知,这是一个错误,已在 GitHub 上进行了非常深入的讨论。这是链接:https://github.com/microsoft/TypeScript/issues/47357
关于typescript - "Type ' string ' cannot be used to index type ' T '"使用泛型时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71522492/