ES7 Object.entries() in TypeScript not working

前端 未结 4 2180
鱼传尺愫
鱼传尺愫 2020-12-01 20:39

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

const sizeByColor = {
    red: 100,
    green: 500,
};

for ( const [ color, size ] of          


        
相关标签:
4条回答
  • 2020-12-01 21:15

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

    In my case compiler just does not know which tsconfig.json file to use. Pointing it to 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"
    ]
    
    0 讨论(0)
  • 2020-12-01 21:15

    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

    0 讨论(0)
  • 2020-12-01 21:17

    Hm, it looks i forgot to inject core-js polyfill to Object.entries. import 'core-js/fn/object/entries'; With this polyfill transpilation works, but IDE is still complaining about it. When I include @types/core-js directly, IDE is ok, but Typescript will crash due to duplicate declarations in "lib/es2017".. It looks like IDE (WebStorm) cant handle "lib" settings inside tsconfig.json

    EDIT: Yey, i tried to modify WebStorm settings, and after set "Use TypeScript service (experimental)" to true, everything is ok !

    0 讨论(0)
  • 2020-12-01 21:32

    For a standalone Typescript app, I had to add the lib es2019.object to the tsconfig, and import the polyfill to make it work :)

    import 'core-js/es/object/from-entries';
    
    0 讨论(0)
提交回复
热议问题