Reputation: 1269
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
while the method returns string ARCHIVED | IN_PROGRESS
But it works when the method returns to Array `
Upvotes: 1
Views: 151
Reputation: 2290
Spreading myFilters.statuses
will cause spreading Array<Status | TopStatus>
, so the value that you return from this function will return type Array<string | Status | TopStatus>
instead of manually declared 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];
}
Upvotes: 1
Reputation: 31087
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.
Upvotes: 1