[英]Typescript classe how specify that element can be optional
假設有這個接口: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;
}
我的問題是我如何在構造函數中指定薪水參數可以或不可以?
您可以將字段定義為參數構造函數(通過向參數添加可見性修飾符)並將適當的字段和參數標記為可選(但您需要將其放在參數列表的末尾):
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.