Imagine we have a flash message component and it has 2 required fields, severity and message; 2 optional fields, id and dismissable.
In flash-message.reducer.ts
, flash message interface defined as:
export interface FlashMessage {
id: string;
severity: 'success' | 'info' | 'warning' | 'danger';
message: string;
dismissable: boolean;
}
While in flash-message.actions.ts
, flash message interface is built as:
interface MinimumRequiredFlashMessage {
id?: string
severity: 'success' | 'info' | 'warning' | 'danger';
message: string;
dismissable?: boolean;
}
Here both id and dismissable fields are set as optional. Then in create action of flash message, setting default values for id
and dismissable
fields.
export class CreateAction implements Action {
type = ActionTypes.Create;
public payload: FlashMessage;
constructor(public minimumPayload: MinimumRequiredFlashMessage) {
this.payload = {
...minimumPayload,
id: minimumPayload.id ? minimumPayload.id : uuid(),
dismissable: isUndefined(minimumPayload.dismissable) ?
true :
minimumPayload.dismissable,
};
}
}
function isUndefined(input: any): input is undefined {
return input === undefined;
}
Both id and dismissable fields are set as default values if not defined.