0
0
Typescriptprogramming~10 mins

Type assertions in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to assert that the variable value is of type string.

Typescript
let value: any = "hello";
let strValue = value as [1];
Drag options to blanks, or click blank then click option'
Aboolean
Bnumber
Cstring
Dobject
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong type in the assertion.
Forgetting to use the as keyword.
2fill in blank
medium

Complete the code to assert that the variable input is of type number.

Typescript
let input: any = 42;
let numInput = [1] as number;
Drag options to blanks, or click blank then click option'
Adata
Binput
Cvalue
DnumInput
Attempts:
3 left
💡 Hint
Common Mistakes
Asserting the wrong variable.
Placing as before the variable.
3fill in blank
hard

Fix the error in the code by completing the type assertion correctly.

Typescript
let data: any = "123";
let length = (data as [1]).length;
Drag options to blanks, or click blank then click option'
Astring
Bnumber
Cboolean
Dobject
Attempts:
3 left
💡 Hint
Common Mistakes
Asserting data as number and trying to access length.
Not using type assertion at all.
4fill in blank
hard

Fill both blanks to assert the variable item as a string and then get its length.

Typescript
let item: any = "typescript";
let len = ([1] as [2]).length;
Drag options to blanks, or click blank then click option'
Aitem
Bnumber
Cstring
Dboolean
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the variable and type in the assertion.
Using the wrong type in the assertion.
5fill in blank
hard

Fill all three blanks to create a type assertion that converts input to a string and then gets the uppercase version.

Typescript
let input: any = "hello";
let upper = ([1] as [2]).[3]();
Drag options to blanks, or click blank then click option'
Ainput
Bstring
CtoUpperCase
DtoLowerCase
Attempts:
3 left
💡 Hint
Common Mistakes
Using toLowerCase instead of toUpperCase.
Asserting the wrong variable or type.