Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES7 Object.entries() in TypeScript not working

Tags:

I have an issue with transpiling ES7 code with TypeScript. This code:

const sizeByColor = {     red: 100,     green: 500, };  for ( const [ color, size ] of Object.entries(sizeByColor) ) {     console.log(color);     console.log(size); } 

gives the error:

TypeError: Object.entries is not a function

TypeScript v2.0.3

tsconfig.json:

{ "compilerOptions": {     "module": "commonjs",     "target": "es6",     "noImplicitAny": true,     "noEmitOnError": true,     "outDir": "dist",     "allowSyntheticDefaultImports": true,     "experimentalDecorators": true,     "pretty": true,     "lib": [ "es2017" ], }, "exclude": [     "node_modules" ], "include": [     "./node_modules/@types/**/*.d.ts",     "./src/**/*.ts" ] } 

I want to iterate trough object with Object.entries(), so I assigned internal definitions "lib": [ "es2017" ], but still, typescript wont allow me to transpile it.

like image 286
Jan Doležal Avatar asked Sep 28 '16 08:09

Jan Doležal


People also ask

What is Object entries()?

Object.entries() returns an array whose elements are arrays corresponding to the enumerable string-keyed property [key, value] pairs found directly upon object . The ordering of the properties is the same as that given by looping over the property values of the object manually.


2 Answers

I can reproduce your problem when I have a global compiler but not a local one in the ./node_modules.

In my case compiler just does not know which tsconfig.json file to use. Pointing it to a particular tsconfig.json file helps:

tsc  --project ./tsconfig.json 

I have also added dom option to the lib, because es2017 does not recognize console:

"lib": [     "es2017",     "dom" ] 
like image 160
Oleksandr Nechai Avatar answered Oct 11 '22 12:10

Oleksandr Nechai


If you don't want to include the full set of ECMAScript 2017 (ES8) in your set of libraries, then you can also use es2017.object to just satisfy the resolution of Object.entries and related.

Here is a minimal working example:

src/index.ts

const sizeByColor = {   red: 100,   green: 500, };  for (const [color, size] of Object.entries(sizeByColor)) {   console.log(color);   console.log(size); } 

tsconfig.json

{   "compilerOptions": {     "lib": ["dom", "es2016", "es2017.object"],     "rootDir": "src",     "target": "es6",     "outDir": "dist"   },   "exclude": [     "node_modules"   ] } 

Note: If "target" is set to "es6", then TypeScript uses by default the following "lib" entries (if none are specified): ["dom", "dom.iterable", "es6", "scripthost"].

The library defaults get overwritten when setting "lib" manually, that's why I needed to add "dom" (to use console.log in my code) and "es6" to demonstrate the usage of ES6 and partial ES8 ("es2017.object").

Source: TypeScript Compiler Options

like image 44
Benny Neugebauer Avatar answered Oct 11 '22 12:10

Benny Neugebauer