TypeScript-联合类型不起作用的函数返回

时间:2019-04-24 11:46:51

标签: typescript

我有一个枚举和一个类型的接口:

export interface Filters {
  cat: Array<string>;
  statuses: Array<Status | TopStatus>;
}

export enum Status {
  ARCHIVED,
  IN_PROGRESS,
  COMING
}

export type TopStatus = Status.ARCHIVED | Status.IN_PROGRESS;

在方法中:

  handleStatuses(myFilters: Filters): Array<string | TopStatus> {
    return [...myFilters.cat, ...myFilters.statuses];
  }

我遇到一个错误2322,他说他正在等待string | ARCHIVED | IN_PROGRESS | COMING,而该方法返回string ARCHIVED | IN_PROGRESS

但是当方法返回数组`

时,它可以工作

2 个答案:

答案 0 :(得分:1)

运行code in the playground会得到:

Type '(string | Status)[]' is not assignable to type '(string | Status.ARCHIVED | Status.IN_PROGRESS)[]'.
  Type 'string | Status' is not assignable to type 'string | Status.ARCHIVED | Status.IN_PROGRESS'.
    Type 'Status.COMING' is not assignable to type 'string | Status.ARCHIVED | Status.IN_PROGRESS'.

特别是:

  

类型'Status.COMING'不能分配给类型'string | Status.ARCHIVED |状态。IN_PROGRESS'。

您试图将枚举分配给只接受其值子集的类型。

答案 1 :(得分:1)

扩展myFilters.statuses将导致扩展Array<Status | TopStatus>,因此从此函数返回的值将返回类型Array<string | Status | TopStatus>,而不是手动声明的Array<string | TopStatus>。这是绝对正确的,一切都按设计进行:)

如果确定函数中的myFilters.statuses仅包含TopFilter,则可以强制重新键入:

handleStatuses(myFilters: Filters): Array<string | TopStatus> {
    return [...myFilters.cat, ...(myFilters.statuses as Array<TopStatus>)];
}

或以正确的方式重新声明函数的返回类型:

handleStatuses(myFilters: Filters): Array<string | Status | TopStatus> {
    return [...myFilters.cat, ...myFilters.statuses];
}