diff options
author | Piotr Monwid-Olechnowicz <hasparus@gmail.com> | 2019-07-03 23:15:10 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-07-03 23:15:10 +0200 |
commit | 96b65fb40d84ce97b6ca7b814e210a61bca294df (patch) | |
tree | 1e12b6440b0d18f902ec27f97eaac0eb08ea788f /typescript.html.markdown | |
parent | 84cb0e88995b6d2f04a119cc25a695a33e1cbf9f (diff) |
[typescript/en] Add tagged union types
They're super useful.
https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions
https://mariusschulz.com/blog/typescript-2-0-tagged-union-types
Diffstat (limited to 'typescript.html.markdown')
-rw-r--r-- | typescript.html.markdown | 13 |
1 files changed, 13 insertions, 0 deletions
diff --git a/typescript.html.markdown b/typescript.html.markdown index 55d8cefe..293a4a35 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -224,6 +224,19 @@ moreNumbers.push(5); // Error, no push method (because it mutates array) moreNumbers.length = 3; // Error, length is read-only numbers = moreNumbers; // Error, mutating methods are missing +// Tagged Union Types for modelling state that can be in one of many shapes +type State = + | { type: "loading" } + | { type: "success", value: number } + | { type: "error", message: string }; + +declare const state: State; +if (state.type === "success") { + console.log(state.value); +} else if (state.type === "error") { + console.error(state.message); +} + // Iterators and Generators // for..of statement |