简体   繁体   中英

TypeScript - Union type not working function return

I have an interface an enum and a type :

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;

And in the method:

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

I have the error 2322 who says he's waiting string | ARCHIVED | IN_PROGRESS | COMING string | ARCHIVED | IN_PROGRESS | COMING string | ARCHIVED | IN_PROGRESS | COMING while the method returns string ARCHIVED | IN_PROGRESS string ARCHIVED | IN_PROGRESS

But it works when the method returns to Array `

Running that code in the playground gives:

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'.

Specifically:

Type 'Status.COMING' is not assignable to type 'string | Status.ARCHIVED | Status.IN_PROGRESS'.

You're trying to assign an enum to a type that only accepts a subset of its values.

Spreading myFilters.statuses will cause spreading Array<Status | TopStatus> Array<Status | TopStatus> , so the value that you return from this function will return type Array<string | Status | TopStatus> Array<string | Status | TopStatus> Array<string | Status | TopStatus> instead of manually declared Array<string | TopStatus> Array<string | TopStatus> . This is clearly and absolutely right, everything is working as designed :)

If you are sure, that myFilters.statuses inside of your function is only includes TopFilter , you can force retyping:

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

or redeclare the return type of the function in correct way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM