假设具有此接口: 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;
}
我的问题是我如何在构造函数中指定薪水参数可以或不能?
答案 0 :(得分:1)
您只需将字段定义为参数构造函数(通过向参数添加可见性修饰符),然后将适当的字段和参数标记为可选(但您需要将其放在参数列表的末尾):>
interface ObjectToSellInterface{
name: string;
salary?: number;
date: Date;
}
export class ObjectToSell implements ObjectToSellInterface{
public constructor(
public name: string,
public date: Date,
public salary?: number){ }
}
上面的代码等同于:
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;
}
}