如何在 TypeScript 中为类的所有属性赋值? [英] How to assign values to all properties of class in TypeScript?

查看:56
本文介绍了如何在 TypeScript 中为类的所有属性赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有私有属性的类:

I have a class with private properties:

class A implements IA {
   private id: number;
   private name: string;

   constructor(obj: IA) {
      // Set here properties from obj
   }
}

我想在创建实例 A 时传递带有初始化值的对象 IA,并仅在我传递的类中重新填充该属性.

I want to pass object IA with initialized values when I create instance A, and refill only that properties in class, which I passed.

new A({id: 1})new A({id: 1, name: "O"})

如何在 TypeScript 中执行此操作?

How to do this in TypeScript?

推荐答案

最简单的方法是使用 Object.assign.它只会复制构造函数参数中指定的文件.

The simplest way to do this is to just use Object.assign. It will only copy the fileds specified in the constructor parameter.

interface IA{
    id? : number;
    name? : string
}

class A {
    private id: number;
    private name: string;

    constructor(obj: IA) {
        Object.assign(this, obj)
    }
}

注意我从类中删除了实现,因为私有字段不能作为接口的实现

Note I removed the implements from the class since private fields can't be the implentation for an interface

这篇关于如何在 TypeScript 中为类的所有属性赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆