Theo's Typesafe CultTTC
Theo's Typesafe Cult4y ago
24 replies
JulieCezar

[TypeScript] How would you go about creating an Array that can have different types of objects?

Firstly sorry if this isn't the right place to ask TS question, but I didn't know where else to ask 😢

I have a dilemma in a project I am working on. The example I will give is not how we do it, but you should get the idea... The project is about task solving and because of some cases we have decided to have a type like so:

type User = {
  id: string,
  name: string,
  tasks: Array<TaskType1 | TaskType2 | TaskType3>
}

Where the tasks array holds all the user's tasks. But like you can see anyone of these elements in the array can be of a completely different type. What I want to do is render a different component based on what type of object it is, so I do this:

const user: User = {...}

user.tasks.map((x) => {
  return <Component />
})


However, since it doesn't know what type it is, I don't get type safety. How can I check which type it is? Is that even possible?

Also, keep in mind that in the future we might add more task types so I have to take that into account as well.
Was this page helpful?