相关疑难解决方法(0)

TypeScript - 传递给构造函数整个对象

我在 type script 上有一堂课:

export class Child {
  name:string;
  age:number;
}
Run Code Online (Sandbox Code Playgroud)

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

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

myFirebaseService.getChild(id).then(function(child){
  var currentChild = new Child(child);
}) 
Run Code Online (Sandbox Code Playgroud)

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

currentChild = {"name":"ben"}
Run Code Online (Sandbox Code Playgroud)

因为“颜色”不是“孩子”的领域。

我试过这个:

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

  constructor(tempChild:Child = null) {
    if (tempChild){
      for (var prop in tempChild) {
        this[prop] = tempChild[prop];
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但它没有帮助。“currentChild”获取所有字段并将它们附加到类实例。

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

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

  constructor(tempChild:Child = null) {
    if (tempChild){
      this.nam  = tempChild.name;
      this.age =tempChild.ageÏ;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

,但我的真理课有很多字段,我想要短代码)

constructor copy-constructor typescript

12
推荐指数
3
解决办法
1万
查看次数

TypeScript:不允许多个构造函数实现

我有一个对象,我在多个服务中使用它,每个服务都应该接受一些参数,所以我创建了两个构造函数,但 TypeScript 不允许我这样做,我的例子是:

class User {
   id: number;
   username: string;
   password: string;
   email: string;
   firstName: string;
   lastName: string;
   roles: string[];

   constructor(username: string, password: string){
       this.username = username;
       this.password = password;
   }

   constructor(id: number, username: string, firstname: string, lastname: string, roles: string[]){
       this.id = id;
       this.username= username;
       this.firstname= firstname;
       this.lastname= lastname;
       this.roles = roles;
   }
   //.. and maybe another constructor also
}
Run Code Online (Sandbox Code Playgroud)

请问有什么技巧可以解决这个问题吗?


例如,当我?在构造函数中使用 Optional时:

constructor(
    public id?: number,
    public username?: string,
    public email?: string,
    public password?: string,
    public …
Run Code Online (Sandbox Code Playgroud)

typescript angular

7
推荐指数
1
解决办法
8796
查看次数

打字稿用数组传播深拷贝

我对打字稿中的展开运算符感到困惑

当我使用 .the spread 运算符制作 object1 的副本时。

  var object2 =  { ...object1, };
Run Code Online (Sandbox Code Playgroud)

即使 object1 包含其他对象,我也会得到一个新的 object2,其中包含所有 object1 项目的深层副本。

However if object1 has an array in it a shallow copy is performed. In that case it seems to maintain the relationship between the array values in object1 and object2.

Is there a way to deep copy arrays using the spread operator?

typescript angular

6
推荐指数
1
解决办法
6310
查看次数

将数组传递给 TypeScript 中的可变参数函数

我有一个方法应该接受一个数字数组或接受可变数量的数字参数(可变参数)。在我使用的大多数语言中,当你创建一个方法/函数可变参数时,它接受两者,但似乎在 TypeScript 中,你不能。当我将这个特定函数设为可变参数时,我提供number[]编译失败的所有地方。

签名供参考(在课堂上ObjectIdentifier):

constructor(... nodes : number[]) {
Run Code Online (Sandbox Code Playgroud)

这失败了:

return new ObjectIdentifier(numbers);
Run Code Online (Sandbox Code Playgroud)

哪里numbers是类型number[]

typescript

3
推荐指数
2
解决办法
1759
查看次数