VS2017中调用[]keys()报错:类型'any[]'无'keys'属性原因咨询
Let's break down exactly why this error is popping up for you:
ES6 Array Methods Aren't Included in Your Type Definitions
TypeScript 2.8, when targeting ES5 (the default setup for many projects), doesn't automatically load type definitions for ES6+ array methods likekeys(). Thekeys()method was added to arrays in ES2015, so if your compiler target is set to ES5, TypeScript's default type library only covers ES5-era features. Since it doesn't recognizekeys()as a valid method on arrays, it throws that error.Missing Library (lib) Configuration in
tsconfig.json
Even if you're targeting a newer ES version, if yourtsconfig.jsondoesn't explicitly include thees2015(or higher) library, TypeScript won't load the type definitions for ES2015 features. Without those definitions, it can't validate thatkeys()exists on an array.Potential Syntax Misunderstanding
It's also possible you're mixing up two similar operations:Array.prototype.keys(): Returns an iterator for the array's indices (an ES6+ feature)Object.keys(yourArray): Returns an array of string-based indices (works in ES5)
If you intended to use the latter but accidentally called.keys()directly on the array, TypeScript will flag this if ES6 types aren't available.
Quick Checks to Confirm the Cause
To verify this is the root issue, you can:
- Open your
tsconfig.jsonand set"target": "es2015"or higher - Add
"lib": ["es2015", "dom"]to yourtsconfig.jsonto include ES2015 type definitions - If you need to stay on ES5, swap
yourArray.keys()withObject.keys(yourArray)
内容的提问来源于stack exchange,提问作者Serj-Tm

