I’m trying to build an array with two possible value types:
type Loading = {
loading: true
}
type Loaded = {
loading: false,
date: string,
value: number,
}
type Items = Loading | Loaded
const items: Items[] = []
so far so good, but now I try to pick value by .find method:
const firstLoaded = items.find(({ loading }) => !loading)
and firstLoaded should be a type of Loaded|undefined – how to make TS know that type?
console.log(firstLoaded?.date) // doesnt work
and 2nd question: how to change value from Loading to Loaded in array:
const firstUnloaded = items.find(({ loading }) => loading)
firstUnloaded.loading = false // doesnt work
>Solution :
For the first question, this might be a good use case for type guards:
function isLoaded(item: Items): item is Loaded {
return (item as Loaded).loading === false;
}
if (isLoaded(item)) {
console.log(firstLoaded.date) // Should work
}
For the second one, I think you can’t just convert it like that. Instead you need to replace array element with another element, for example by assigning it directly like items[index] = convertToLoaded(items[index])