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

最近开始做webpack集成ts编译环境的工作,遇到很多问题,这里记录一下吧

今天的问题是在使用Object.assign的时候,编辑器报错了,提示Property ‘assign’ does not exist on type ‘ObjectConstructor’。

查了好久的资料找到几种解决方法:

利用hack写法

还没搞清楚原理,暂时先这么叫吧

——- 2018-08-22 14:10:35 补充:此写法再ts里称为断言,请参考TypeScript 基础类型

1
(<any>Object).assign({}, {})

在tsconfig.json中增加lib

1
2
3
4
5
6
7
8
{
"compilerOptions": {
// ...
"target": "es5",
"lib": ["es2015", "es2017", "dom"]
// ...
}
}

利用ES6 展开运算符 Spread operator 代替assign

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

自己加语法糖

如果使用的是非npm或webpack环境,那直接粘贴以下代码到你的代码里就好了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
});
}

参考 developer.mozilla.org

本文永久链接: https://www.mulianju.com/property-assign-does-not-exist-on-type-objectconstructor/