Using TypeScript, and Object.assign gives me an error “property 'assign' does not exist on type 'ObjectConstructor'”

后端 未结 3 1295
情深已故
情深已故 2020-12-29 01:22

I am writing my question again because earlier it made little sense and I wasn\'t very clear.

I am receiving data from API that looks something like this:

         


        
相关标签:
3条回答
  • 2020-12-29 01:59

    For typescript version 2.0 or higher, just modify the tsconfig.json file so the "lib" section includes "es6":

    "lib": [
      "es5",
      "es6",
      "dom",
      "es2015.collection"
    ]
    
    0 讨论(0)
  • 2020-12-29 02:05

    With Typescript 2.1 or higher, you can use Object spread syntax instead.

    let obj = { x: 1, y: "string" };
    var newObj = {...obj, z: 3, y: 4}; // { x: number, y: number, z: number }
    

    The order of specifying spread operations determines what properties end up in the resulting object; properties in later spreads “win out” over previously created properties.

    0 讨论(0)
  • 2020-12-29 02:16

    Object.assign is an ECMAScript2015 feature and does not exist in ECMAScript5 and lower.

    You're most likely targeting to compile your Typescript for ECMAScript5 and therefor the Object interface does not have assign defined.

    You can either target ECMAScript2015 by changing your TS compiler configuration with

    target: 'es6'

    or you can extend the ObjectConstructor interface with the method assign

    declare interface ObjectConstructor {
        assign(...objects: Object[]): Object;
    }
    

    (you can add this declaration anywhere, redeclaring an interface extends it instead of overwriting it)

    Or you can coerce Object to any and ignore its typing:

    (<any>Object).assign( this.photos, photos )

    Whichever you choose, keep in mind that if you want this to run on older browsers you need to add a polyfill. Most modern browsers are fairly close to implementing the ES2015 feature set, but they're not 100% there, meaning that some parts of your code will still fail if you rely on ES2015 functionality.

    Typescript will not polyfill Object.assign when targetting ES5 or older, that is why you are getting this error. On the other hand, Babel does have polyfills in the form of plugins, which would mean you need to incorporate Babel transpilation into your build pipeline, see: https://babeljs.io/docs/plugins/transform-object-assign/

    As a final option you can consider using a library as Lodash or jQuery, which have their own implementation of Object.assign (called extend)

    0 讨论(0)
提交回复
热议问题