typescript - "Type ' string ' cannot be used to index type ' T '"使用泛型时

标签 typescript

我在 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'
}

Playground link

这对我来说毫无意义,考虑到以下事实实际上没有错误,这就更加荒谬了:

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/

相关文章:

javascript - 类型 'csrf_token' 上不存在属性 'Object'

typescript - 在手写的 d.ts 文件中,如何从模块根目录中的一个命名空间公开函数?

javascript - Angular 5 : Argument of type 'void' is not assignment to parameter of type '{} | PromiseLike<{}>'

reactjs - Prop 的 TypeScript 条件类型

node.js - Volta 与yarn run 构建系统找不到指定的路径

angular - 类型上不存在属性

node.js - Node 的 WebStorm 代码完成显示太多选项

javascript - RxJS zip 和管道组合不起作用

javascript - TypeScript 闭包范围错误 : The name does not exist in the current scope

typescript :重载函数的返回类型