如何在TypeScript中强制执行导出函数的类型?

时间:2018-01-04 15:05:56

标签: typescript

我有这个:

export const counterReducer: ActionReducer<number> = (state = 0, action: Action) => {
  const at = CounterActions;
  switch (action.type) {
    case at.incrementId:
      return state + 1;

    case at.decrementId:
      return state - 1;

    case at.resetId:
      return 0;

    default:
      return state;
  }
};

不幸的是,我不得不将其重写为export function形式(没有它,AoT不会工作):

export function counterReducer(state = 0, action: Action): number {
  const at = CounterActions;
  switch (action.type) {
    case at.incrementId:
      return state + 1;

    case at.decrementId:
      return state - 1;

    case at.resetId:
      return 0;

    default:
      return state;
  }
}

正如你所看到的,我已经失去了整个函数的类型(ActionReducer<number>),这对我来说是不可接受的。

所以问题是:
如何export function构造类型?如何在定义中键入它?

1 个答案:

答案 0 :(得分:0)

您可以导出类似的类型函数:

export const counterReducer = (state = 0, action: Action) => ({
  ..
} as ActionReducer<number>);