Typescript中使用Object.assign报错 : Property ‘assign’ does not exist on type ‘ObjectConstructor’

在Typescript中使用Object.assign报错:Property ‘assign’ does not exist on type ‘ObjectConstructor’


使用引擎编译后的ts会转为js,方法是可以用的,主要是为了解决在ts中使用该方法编译器报错

解决方法:

使用类型断言(Type Assertion),对Object进行具体类型的指定(指定不是转换

(<any>Object).assign(obj1, obj2);

Object.assign是浅拷贝,知道原理就可以重写一个新的方法

当然,这只是重写这个方法,不是解决上面的问题

下面这段代码来自:Object.assign 原理及其实现——@木易杨

if (typeof Object.assign2 != 'function') {
  // Attention 1
  Object.defineProperty(Object, "assign2", {
    value: function (target) {
      'use strict';
      if (target == null) { // Attention 2
        throw new TypeError('Cannot convert undefined or null to object');
      }

      // Attention 3
      var to = Object(target);
        
      for (var index = 1; index < arguments.length; index++) {
        var nextSource = arguments[index];

        if (nextSource != null) {  // Attention 2
          // Attention 4
          for (var nextKey in nextSource) {
            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey];
            }
          }
        }
      }
      return to;
    },
    writable: true,
    configurable: true
  });
}
//使用方法
Object.assign2(obj1, obj2);

维尼聚合工具


猜你喜欢

转载自blog.csdn.net/S_clifftop/article/details/106428180
今日推荐