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);


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.


"This is type 'any'"
"Type of stringValue:"

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.

Follow us on Facebook and Twitter for latest update.