I have the following loadMore function that returns Promise<Project[] | Folder[] | undefined>.
const items = await loadMore();
I want to cast the type of items to Folder[]. How do I do that using typescript?
CodePudding user response:
This is another way of doing it :
const items: Folder[] = loadMore()
CodePudding user response:
Using a type assertion:
const items = await loadMore() as Folder[];
However, it's safer to discriminate the union.
CodePudding user response:
I would offer that it's better to discriminate the items of the array with the following inline type-discriminator used as the predicate in Array.filter
const folderItems = items?.filter(
(v: Folder | Project): v is Folder => /* is v really a Folder? true/false */
);
to give you either an array that you can be sure contains only Folder items, or undefined if items is undefined.
