Hacker Timesnew | past | comments | ask | show | jobs | submitlogin

In Typescript at least, if the discriminated union is set up correctly, you just need a single check of the type field. That lets TS narrow the type so it knows whether e.g. `.posts` is present or not.


I think I can do this, yes, but it becomes a very large amount of repetitive work.

Let's say I have api/profile (which has `.posts`) and api/user-directory (which does not). I define User as a discriminated union - one has type `user-with-posts` and one has type `user-no-posts`. OK, good so far. But now say I have a photo gallery, which returns photos on user. Now I have to add that into my discriminated union type, e.g. `user-with-posts-and-photos`, `user-with-posts-but-not-photos`, `user-with-no-posts-but-yes-photos`... and it gets worse if I also have another page with DMs...


You can use a string union to discriminate when it makes sense, but that's not the only way to discriminate and in this case you'd instead use the presence of the items themselves (essentially duck-typing with strong type guarantees)

Typescript playground: https://www.typescriptlang.org/play/?#code/C4TwDgpgBACg9gZ2F...


Now you run into the issue I mentioned in GP, where you end up writing `if (blah)` everywhere, even though you know that `blah` is definitely present.


Change the design of the API so that the posts and the photos and so on are not returned inside the user object but on the same level as it.

So {user: {...}, photos: [...]}, not {user: {..., photos: [...]}}.

Alternatively define separate schemas for each endpoint that extend the base User schema. But I'd prefer having the same structure everywhere as much as possible.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: