Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Union type in array – how to set/change value

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Playground

>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])

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading