Angular Typescript类如何指定该元素可以是可选的

Angular Typescript类如何指定该元素可以是可选的,angular,typescript,Angular,Typescript,假设有此接口: Employee.model.ts: interface EmployeeInterface{ name: string; salary?: number; date: Date; } 我知道我该怎么做: export class Employee implements EmployeeInterface{ public name: string; public salary: number; public date: Date;

假设有此接口: Employee.model.ts:

interface EmployeeInterface{
    name: string;
    salary?: number;
    date: Date;
}
我知道我该怎么做:

export class Employee implements EmployeeInterface{
    public name: string;
    public salary: number;
    public date: Date;
}

我的问题是如何在构造函数中指定薪资参数可以是或不可以是?

您可以将字段定义为参数构造函数(通过向参数添加可见性修饰符),并将适当的字段和参数标记为可选(但您需要将其放在参数列表的末尾):

上述代码相当于:

export class ObjectToSell implements ObjectToSellInterface{

  public name: string;
  public date: Date;
  public salary?: number;

  public constructor(
    name: string,
    date: Date, 
    salary?: number){ 
      this.date = date;
      this.name = name;
      this.salary = salary;
    }
}

@Doflamingo19取决于你想做什么。私有字段不能是接口实现的一部分。如果您正在考虑使用私有fiedls并创建公共get/set属性,请不要!这不是常见的JS/TS实践。如果需要,您可以稍后将该字段更改为属性。@Doflamingo19您可以使用它们,但是如果您要做的只是在设置属性时返回一个私有字段/设置私有字段,那么使用它们就没有意义了。
export class ObjectToSell implements ObjectToSellInterface{

  public name: string;
  public date: Date;
  public salary?: number;

  public constructor(
    name: string,
    date: Date, 
    salary?: number){ 
      this.date = date;
      this.name = name;
      this.salary = salary;
    }
}