Typescript classe how specify that element can be optional

Viewed 31

Suppose to have this Interface: Employee.model.ts:

interface EmployeeInterface{
    name: string;
    salary?: number;
    date: Date;
}

I know how I can do :

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

My question is how I specify in the constructor that salary parameters can be or not canno't be?

1 Answers

You can just define the fields as parameter constructors (by adding a visibility modifier to the parameter) and mark the apropriate field and parameter as optional (but you will need to put it at the end of the parameter list):

interface ObjectToSellInterface{
  name: string;
  salary?: number;
  date: Date;
}
export class ObjectToSell implements ObjectToSellInterface{
  public constructor(
    public name: string,
    public date: Date, 
    public salary?: number){ }
}

The above code would be equivalent to:

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;
    }
}
Related