summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authordavidgtu <david.giahuy.tu@gmail.com>2019-10-11 15:53:07 -0400
committerdavidgtu <david.giahuy.tu@gmail.com>2019-10-11 15:53:07 -0400
commit0e437a75db091eb5cb057f1a49bf07db562d1d8f (patch)
treee95f412faf25fbf71b636c7f9ca8e27e5b21c7a9
parentf0eb830ebded612e53eef019776d6573fbc42ab0 (diff)
add type assertion
-rw-r--r--typescript.html.markdown16
1 files changed, 16 insertions, 0 deletions
diff --git a/typescript.html.markdown b/typescript.html.markdown
index cf2111d5..6c6da2c4 100644
--- a/typescript.html.markdown
+++ b/typescript.html.markdown
@@ -257,8 +257,24 @@ for (const i in list) {
console.log(i); // 0, 1, 2
}
+// Type Assertion
+let foo = {} // Creating foo as an empty object
+foo.bar = 123 // Error: property 'bar' does not exist on `{}`
+foo.baz = 'hello world' // Error: property 'baz' does not exist on `{}`
+// Because the inferred type of foo is `{}` (an object with 0 properties), you
+// are not allowed to add bar and baz to it. However with type assertion,
+// the following will pass:
+
+interface Foo {
+ bar: number;
+ baz: string;
+}
+
+let foo = {} as Foo; // Type assertion here
+foo.bar = 123;
+foo.baz = 'hello world'
```