-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
4bde766
commit 024990d
Showing
2 changed files
with
18 additions
and
0 deletions.
There are no files selected for viewing
7 changes: 7 additions & 0 deletions
7
4-sophisticated-type-manipulation/4-2-using-type-assertion/exampleJsonString.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
let jsonString: string = '{"name": "John", "age": 30}'; | ||
|
||
// We know the structure of JSON, assert the type | ||
let userInfo: { name: string; age: number } = JSON.parse(jsonString) as { name: string; age: number }; | ||
|
||
console.log(userInfo.name); // Outputs: John | ||
console.log(userInfo.age); // Outputs: 30 |
11 changes: 11 additions & 0 deletions
11
4-sophisticated-type-manipulation/4-2-using-type-assertion/usingTypeAssertion.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
let someValue: any = "this is a string"; | ||
|
||
let strLength: number = (someValue as string).length; | ||
|
||
console.log(strLength); // Outputs the length of "someValue" | ||
|
||
let someValue2: any = "this is another string"; | ||
|
||
let strLength2: number = (<string>someValue).length; | ||
|
||
console.log(strLength2); // Outputs the length of "someValue" |