From 96b65fb40d84ce97b6ca7b814e210a61bca294df Mon Sep 17 00:00:00 2001 From: Piotr Monwid-Olechnowicz Date: Wed, 3 Jul 2019 23:15:10 +0200 Subject: [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 --- typescript.html.markdown | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'typescript.html.markdown') 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 -- cgit v1.2.3 From 7fa8cc63c85f331e81a51443d9a81a9e058e8f42 Mon Sep 17 00:00:00 2001 From: Monis Qadri Date: Wed, 31 Jul 2019 13:06:54 +0530 Subject: Update typescript.html.markdown The input list is of int[] [@line236](https://github.com/adambard/learnxinyminutes-docs/blame/master/typescript.html.markdown#L236]) but the output of its shown is in string [@line238](https://github.com/adambard/learnxinyminutes-docs/blame/master/typescript.html.markdown#L238]). same thing happens at [@line244](https://github.com/adambard/learnxinyminutes-docs/blame/master/typescript.html.markdown#L244]) --- typescript.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'typescript.html.markdown') diff --git a/typescript.html.markdown b/typescript.html.markdown index 55d8cefe..c27e93a6 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -235,13 +235,13 @@ for (const val of arrayOfAnyType) { let list = [4, 5, 6]; for (const i of list) { - console.log(i); // "4", "5", "6" + console.log(i); // 4, 5, 6 } // for..in statement // iterate over the list of keys on the object being iterated for (const i in list) { - console.log(i); // "0", "1", "2", + console.log(i); // 0, 1, 2 } -- cgit v1.2.3