3 ms·
Tagged union types [0] are very powerful and let you model most things in very robust ways. type Response<Data, Error = string> = | { type: "Loading" }
by gherkinnn 5y ago
Tagged union types [0] are very powerful and let you model most things in very robust ways.
type Response<Data, Error = string> =
| { type: "Loading" }
| { type: "Success", data: Data }
| { type: "Error", message: Error }
You won't have access to data unless type === "Success". You can model other mutually exclusive situations in the same way.
Then, Typescript comes with very handy utility types. [1]
And if you're having an especially good day, you can loose yourself in type level programming. Mapped types, for example. [2] Though this is only really necessary at a library level.
Back in reality, type narrowing [3] and function overloading [4] are good to know about.
And there's a lot more.
- 0 https://mariusschulz.com/blog/tagged-union-types-in-typescript https://mariusschulz.com/blog/tagged-union-types-in-typescri...
- 1 https://www.typescriptlang.org/docs/handbook/utility-types.html https://www.typescriptlang.org/docs/handbook/utility-types.h...
- 2 https://www.typescriptlang.org/docs/handbook/2/mapped-types.html https://www.typescriptlang.org/docs/handbook/2/mapped-types....
- 3 https://www.typescriptlang.org/docs/handbook/2/narrowing.html https://www.typescriptlang.org/docs/handbook/2/narrowing.htm...
- 4 https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads https://www.typescriptlang.org/docs/handbook/2/functions.htm...