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

Time:11-05

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

CodePudding user response:

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;
  • Related