Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type cannot be used as an index type

Go to https://www.typescriptlang.org/play/index.html and paste:

let userTypes = {};
let keys = Object.keys[userTypes];

receive error:

error TS2538: Type '{}' cannot be used as an index type.

Why?

like image 815
Eu Insumi Prunc Avatar asked Dec 30 '16 18:12

Eu Insumi Prunc


People also ask

Which indexing Cannot be used in an array?

You can't index an array using an object; you must use a number to represent the offset from the start of the array.

What is an index type?

Indexing is a small table which is consist of two columns. Two main types of indexing methods are 1)Primary Indexing 2) Secondary Indexing. Primary Index is an ordered file which is fixed length size with two fields. The primary Indexing is also further divided into two types 1)Dense Index 2)Sparse Index.

Has an any type because expression of type string can't be used to index?

The error "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type" occurs when we use a string to index an object with specific keys. To solve the error, type the string as one of the object's keys.

Does not exist on type TypeScript?

The "Property does not exist on type '{}'" error occurs when we try to access or set a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names. Copied!


1 Answers

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.

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 a problem 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:

let keys = Object.keys(userTypes);

It calls keys with userTypes instead of index with it.

like image 148
Carcigenicate Avatar answered Oct 20 '22 21:10

Carcigenicate