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进行具体类型的指定(指定不是转换),使用<>as 关键字都可以,指定为any

(<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);

维尼聚合工具


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值