diff options
author | Divay Prakash <divayprakash@users.noreply.github.com> | 2020-01-11 14:23:22 +0530 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-01-11 14:23:22 +0530 |
commit | a6c71dae3d259744854c0779784067b5c6c8132d (patch) | |
tree | 0d6de3043b57d27a7d8dafebf5cefb38d097b54d | |
parent | 194d3ae7abb6394235d0c5605214584e90df3a29 (diff) | |
parent | 0e437a75db091eb5cb057f1a49bf07db562d1d8f (diff) |
Merge pull request #3694 from davidgtu/ts/type-assertion
[en/typescript] add type assertion section
-rw-r--r-- | typescript.html.markdown | 16 |
1 files changed, 16 insertions, 0 deletions
diff --git a/typescript.html.markdown b/typescript.html.markdown index 00f0cbc5..7e857cc0 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' ``` |