Type assertion in TypeScript
TypeScript Advance Types: Exercise-7 with Solution
Write a TypeScript program that declares a variable as type any and uses a type assertion to explicitly cast it to type string.
Sample Solution:
TypeScript Code:
// Declare a variable 'anyValue' as type 'any'
let anyValue: any = "This is type 'any'";
// Use a type assertion to cast 'anyValue' to type 'string'
let stringValue: string = anyValue as string;
// Print the value and type of 'stringValue'
console.log("stringValue:", stringValue);
console.log("Type of stringValue:", typeof stringValue);
Explanations:
In the exercise above,
- First, declare a variable 'anyValue' as type "any". When a variable is of type "any", it can hold values of any type without type checking.
- Assign a string value to 'anyValue'.
- Use a type assertion to explicitly cast anyValue to type string.
- Declare a variable stringValue as type 'string' and assign the casted value to it.
- Finally, we print the value and the type of stringValue to the console.
Output:
"stringValue:" "This is type 'any'" "Type of stringValue:" "string"
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: Extracting Numbers, Booleans, and Strings from a Mixed TypeScript Array.
Next: Calculating length of strings in TypeScript.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/typescript-exercises/typescript-advance-types-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics