Jon_B
Jon_B

Reputation: 1079

In Typescript, how can I specify the return type of a function that can return multiple types?

I have a reusable method getFilters that can return a number of different types

getFilters(): IListFilteringType {...}
type IListFilteringTypeMultiSelect = (string | number)[];
type IListFilteringType = boolean | string | number | IListFilteringTypeMultiSelect;

When I call getFilters how can I specify that I know that the returned value with be of type IListFilteringTypeMultiSelect and not one of the other possible values of IListFilteringType?

Thank you

Upvotes: 0

Views: 78

Answers (1)

Woohaik
Woohaik

Reputation: 1354

If you are sure about the type of the return of the function for a particular execution, you could cast the return value using as.

const variable = functionResponse as IListFilteringTypeMultiSelect;

Upvotes: 0

Related Questions