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?
You can't index an array using an object; you must use a number to represent the offset from the start of the array.
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.
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With