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

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

问题描述

我在类型脚本处有一个课:

  export class Child {
name:string;
年龄:人数;
}

我想强制类实例仅具有类声明具有的属性。 / p>

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

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

因此,当对象为:{name: ben,color: db}时,我希望结果为:

  currentChild = { name: ben} 

因为颜色不是孩子的字段。



我尝试过:

  export class Child {
name:string;
年龄:人数;

构造函数(tempChild:Child = null){
if(tempChild){
for(tempChild中的var prop){
this [prop] = tempChild [prop ];
}
}
}
}

但是这没有帮助。 currentChild获取所有字段并将其附加到类实例。



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

 出口类别儿童{
name:string;
age:number;

构造函数(tempChild:Child = null){
if(tempChild){
this.nam = tempChild.name;
this.age =tempChild.ageÏ;
}
}
}

,但是我的真理类有很多字段,并且我想要短代码)

解决方案

我们想要的:



  • 一次声明类字段

  • 在我们的类中有方法


解决方案:

  class Animal {
name:string ='default value';
组:字符串=默认值;

构造函数(data:Partial< Animal> = {}){
Object.assign(this,data)
}

echo(){
return`我的名字是$ {this.name},我来自:$ {this.group}`;
}
}

类Dog扩展动物{
echo(){
return super.echo()+’from Dog class’;
}
}

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

动物-根类


-嵌套类


所有工作都没有打字错误,


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.

For example, if I get from firebase an object:

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

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".

I tried this:

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

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

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

(Of course, I can use the following code:

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

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

, but my truth class has many fields, and I want short code)

解决方案

What we want:

  • one time declare class fields
  • have methods in our class

Solution:

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 - root class

Dog - nested class

All works without typescript errors

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

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