对Union进行约束的函数键入

时间:2019-06-22 19:54:07

标签: typescript

我有此代码:

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

1 个答案:

答案 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