我有此代码:
export type Command = { aggregateId: string }
export type AddTask = Command & { name: string, dueDate: Date }
export type Commands =
| AddTask
| RemoveTask
| CompleteTask
| ChangeDueDate
export type Event = { aggregateId: string }
export type TaskAdded = Event & { name: string, dueDate: Date }
export type Events =
| TaskAdded
| TaskRemoved
| TaskCompleted
| TaskDueDateChanged
export type CommandHandler<T extends Commands> = (command: T) => Events | DomainError
我如何将此function
注释为CommandHandler<AddTask>
类型
export function AddTaskCommandHandler (command: AddTask): Events {
const event: TaskAdded = { aggregateId: command.aggregateId, dueDate: command.dueDate, name: command.name }
return event
}
我还要确保我只能返回Event
联合身份的成员Events
。
答案 0 :(得分:1)
您可以使用匿名函数值将函数声明重写为var
。然后将var明确键入CommandHandler<AddTask>
,然后typescript会推断/类型检查值。
export var AddTaskCommandHandler: CommandHandler<AddTask> = function(command) {
const event: TaskAdded = { aggregateId: command.aggregateId, dueDate: command.dueDate, name: command.name }
return event
}
此处将command
推断为AddTask
,并将返回类型检查为Events | DomainError
。