TypeScript - 传递给构造函数整个对象 [英] TypeScript - pass to constructor entire object

查看:23
本文介绍了TypeScript - 传递给构造函数整个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 type script 上有一堂课:

I have a class at type script:

export class Child {
  name:string;
  age:number;
}

我想强制类实例只具有类声明所具有的属性.

I want to force class instances to have only properties that class declaration has.

例如,如果我从 firebase 获取一个对象:

For example, if I get from firebase an object:

myFirebaseService.getChild(id).then(function(child){
  var currentChild = new Child(child);
}) 

所以当对象是:{name:"ben", color:"db"}时,我希望结果是:

So when the object is: {name:"ben", color:"db"}, I want the result to be:

currentChild = {"name":"ben"}

因为颜色"不是孩子"的字段.

Becouse "color" is not field of "child".

我试过了:

export class Child {
  name:string;
  age:number;

  constructor(tempChild:Child = null) {
    if (tempChild){
      for (var prop in tempChild) {
        this[prop] = tempChild[prop];
      }
    }
  }
}

但这无济于事.currentChild"获取所有字段并将它们附加到类实例.

But it is not help. "currentChild" get all of the fields and attached them to the class instance.

(当然,我可以用下面的代码:

export class Child {
  name:string;
  age:number;

  constructor(tempChild:Child = null) {
    if (tempChild){
      this.nam  = tempChild.name;
      this.age =tempChild.ageÏ;
    }
  }
}

,但是我的truth class有很多字段,我想要短代码)

推荐答案

我们想要的:

  • 一次声明类字段
  • 在我们的类中有方法

解决方案:

class Animal {
  name: string = 'default value';
  group: string = 'default value';

  constructor(data: Partial<Animal> = {}) {
    Object.assign(this, data)
  }

  echo() {
    return `My name is ${this.name}, I'm from: ${this.group}`;
  }
}

class Dog extends Animal {
  echo() {
    return super.echo() + ' from Dog class';
  }
}

const dog = new Dog({name: 'Teddy'});
console.log(dog.echo());

Animal - 根类

Dog - 嵌套类

所有作品都没有打字错误

All works without typescript errors

这篇关于TypeScript - 传递给构造函数整个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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