typescript 类型“ObjectConstructor”上不存在属性“assign”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35959372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:59:57  来源:igfitidea点击:

Property 'assign' does not exist on type 'ObjectConstructor'

typescript

提问by uksz

I am using TypeScript in my application, where I use function:

我在我的应用程序中使用 TypeScript,我在其中使用函数:

Object.assign(this.success, success.json())

However, during compilation, I receive the following error:

但是,在编译期间,我收到以下错误:

 error TS2339: Property 'assign' does not exist on type 'ObjectConstructor'.

Do you have any idea how can I get rid of this error?

你知道我怎样才能摆脱这个错误吗?

采纳答案by Amid

You can use type assertion, like this:

您可以使用类型断言,如下所示:

(<any>Object).assign(this.success, success.json())

回答by Rico Kahler

Configure:

配置:

If you're using VS code (or if you see a tsconfig.jsonfile):

如果您使用 VS 代码(或者如果您看到一个tsconfig.json文件):

You should add the libproperty to your tsconfig.jsonand then your editor will use the bundled typescript type definitions and also give you intellisense.

您应该将lib属性添加到您的tsconfig.json,然后您的编辑器将使用捆绑的打字稿类型定义并为您提供智能感知。

Just add the "lib": ["esnext", "dom"]to your tsconfig.jsonand restart VS Code

只需将其添加"lib": ["esnext", "dom"]到您的tsconfig.json并重新启动 VS Code

{
    "compilerOptions": {
        // ...
        "target": "es5",
        "lib": ["esnext", "dom"]
        // ...
    }
}

See all tsconfig.jsonoptions here.

在此处查看所有tsconfig.json选项。

If you're using Visual Studio or MSBuild include this tag:

如果您使用的是 Visual Studio 或 MSBuild,请包含此标签:

<TypeScriptLib>esnext, dom</TypeScriptLib>

See all MSBuild typescript compiler options and usage here.

在此处查看所有 MSBuild typescript 编译器选项和用法。



Check your work:

检查你的工作:

If you've configured your project to use the built-in types and restarted your editor, then your resulting type will look like this instead of the type being anywhen you use Object.assign:

如果您已将项目配置为使用内置类型并重新启动编辑器,则生成的类型将如下所示,而不是any使用时的类型Object.assign

code example 1

代码示例 1



Note on polyfills and older browser compatibility:

关于 polyfills 和旧浏览器兼容性的注意事项:

Notethat if you are transpiling to ES5 or lower and are targeting IE11, you will need to include polyfills because the typescript compiler will not include the polyfills for you.

请注意,如果您要转译到 ES5 或更低版本并针对 IE11,则需要包含 polyfill,因为 typescript 编译器不会为您包含 polyfill。

If you'd like to include the polyfills (which you should) then I would recommend using core-js's polyfills.

如果你想包含 polyfills(你应该这样做),那么我建议使用 core-js 的 polyfills。

npm install --save core-js

or

或者

yarn add core-js

Then in the entry point in your app (e.g. /src/index.ts) add the import for core-jsat the top of the file:

然后在您的应用程序的入口点(例如/src/index.tscore-js在文件顶部添加导入:

import 'core-js';

If you're not using a package manager then you can just paste the following polyfill taken from MDNin some place in your code that runs before the your usage of Object.assign.

如果您没有使用包管理器,那么您可以将以下从 MDN 获取的 polyfill 粘贴到您使用Object.assign.

if (typeof Object.assign != 'function') {
  // Must be writable: true, enumerable: false, configurable: true
  Object.defineProperty(Object, "assign", {
    value: function assign(target, varArgs) { // .length of function is 2
      'use strict';
      if (target == null) { // TypeError if undefined or null
        throw new TypeError('Cannot convert undefined or null to object');
      }

      var to = Object(target);

      for (var index = 1; index < arguments.length; index++) {
        var nextSource = arguments[index];

        if (nextSource != null) { // Skip over if undefined or null
          for (var nextKey in nextSource) {
            // Avoid bugs when hasOwnProperty is shadowed
            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey];
            }
          }
        }
      }
      return to;
    },
    writable: true,
    configurable: true
  });
}

回答by Robert MacLean

This is caused by you using an ECMAScript 6 feature and targeting ECMAScript 5 or 3. Easiest fix is to set the right target, for example if you are using Grunt:

这是由于您使用 ECMAScript 6 功能并以 ECMAScript 5 或 3 为目标造成的。最简单的解决方法是设置正确的目标,例如,如果您使用 Grunt:

options: {
    target: 'es6'
}

of change the relevant property tab in Visual Studio, or manually by editing your .csproj file and finding the TypeScriptTarget element and changing to ES6, for example:

更改 Visual Studio 中的相关属性选项卡,或手动通过编辑 .csproj 文件并找到 TypeScriptTarget 元素并更改为 ES6,例如:

<TypeScriptTarget>ES6</TypeScriptTarget>

If you need to target ES5, then merely add the following to your TypeScript code

如果您需要针对 ES5,那么只需将以下内容添加到您的 TypeScript 代码中

declare interface ObjectConstructor {
    assign(target: any, ...sources: any[]): any;
}

That merges the extra method in, solving the issue. More details here. You may need a polyfill though, depending on your browser compatibilityrequirements - for example this one from MDN:

这合并了额外的方法,解决了这个问题。更多细节在这里。不过,您可能需要一个 polyfill,具体取决于您的浏览器兼容性要求 - 例如来自MDN 的这个:

if (typeof Object.assign != 'function') {
  (function () {
    Object.assign = function (target) {
      'use strict';
      if (target === undefined || target === null) {
        throw new TypeError('Cannot convert undefined or null to object');
      }

      var output = Object(target);
      for (var index = 1; index < arguments.length; index++) {
        var source = arguments[index];
        if (source !== undefined && source !== null) {
          for (var nextKey in source) {
            if (source.hasOwnProperty(nextKey)) {
              output[nextKey] = source[nextKey];
            }
          }
        }
      }
      return output;
    };
  })();
}

回答by Fahd Allebdi

You can use spread operator as in ES6

您可以像在 ES6 中一样使用扩展运算符

const obj = {...this.success,...success.json()};

const obj = {...this.success,...success.json()};

回答by Sergejs

I've added typings:

我添加了类型:

typings install dt~es6-shim --global --save

回答by Davie Dave

Why not use the spread operator?

为什么不使用扩展运算符?

return {this.success, ...success.json() || {}};

return {this.success, ...success.json() || {}};

回答by ForcedFakeLaugh

I know this has been long but here is an easy fix

我知道这已经很长时间了,但这里有一个简单的解决方法

(Object as any).assign(this.success, success.json())