mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-08-09 08:16:58 +02:00
[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
This commit is contained in:
committed by
GitHub
parent
84cb0e8899
commit
96b65fb40d
@@ -224,6 +224,19 @@ moreNumbers.push(5); // Error, no push method (because it mutates array)
|
|||||||
moreNumbers.length = 3; // Error, length is read-only
|
moreNumbers.length = 3; // Error, length is read-only
|
||||||
numbers = moreNumbers; // Error, mutating methods are missing
|
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
|
// Iterators and Generators
|
||||||
|
|
||||||
// for..of statement
|
// for..of statement
|
||||||
|
Reference in New Issue
Block a user