typescript 类型不能用作索引类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41400930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Type cannot be used as an index type
提问by Eu Insumi Prunc
Go to https://www.typescriptlang.org/play/index.htmland paste:
转到https://www.typescriptlang.org/play/index.html并粘贴:
let userTypes = {};
let keys = Object.keys[userTypes];
receive error:
接收错误:
error TS2538: Type '{}' cannot be used as an index type.
Why?
为什么?
采纳答案by Carcigenicate
Object.keys
returns an array of properties. You can't index an array using an object; you must use a number to represent the offset from the start of the array.
Object.keys
返回一组属性。不能使用对象索引数组;您必须使用一个数字来表示距数组开头的偏移量。
As a equivalent example, what do you expect this code to do?:
作为一个等效的例子,你希望这段代码做什么?:
var a = [1, 2, 3, 4]
console.log(a[{}]);
It's nonsensical.
这是荒谬的。
Edit:
After reading the OP's comments and looking over then code again, I realized that my assessment was wrong. While aproblem is that the original code is attempting to index the keys
function using an object literal, the real issue is the use of square brackets instead of parentheses. This will work:
编辑:在阅读 OP 的评论并再次查看代码后,我意识到我的评估是错误的。当一个问题是,原来的代码试图索引keys
功能使用对象文本,真正的问题是使用方括号,而不是括号。这将起作用:
let keys = Object.keys(userTypes);
It calls keys
with userTypes
instead of index with it.
它调用keys
withuserTypes
而不是 index 。