'How to typecast in typescript

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?



Solution 1:[1]

This is another way of doing it :

const items: Folder[] = loadMore() 

Solution 2:[2]

Using a type assertion:

const items = await loadMore() as Folder[];

However, it's safer to discriminate the union.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dorianDevTech
Solution 2