w3resource

TypeScript type conversion example

TypeScript Basic: Exercise-6 with Solution

Write a TypeScript program that converts a variable of one type to another using type assertions and type conversion functions like parseInt().

Sample Solution:

TypeScript Code:

// Using type assertion to convert a string to a number
let str_num: string = "100";
let numberFromAssertion: number = parseInt(str_num); // Using parseInt to convert
console.log("Number from assertion:", numberFromAssertion);

// Using type assertion to convert a number to a string
let numberValue: number = 200;
let stringFromAssertion: string = numberValue.toString(); // Using toString() method to convert
console.log("String from assertion:", stringFromAssertion);

Explanations:

In the exercise above -

  • First, declare a ‘str_num’ variable containing the string "100" and a 'numberValue' variable containing the number 200.
  • To convert a string to a number, we use "parseInt()" to parse the string and obtain a numeric value. We assign the result to the 'numberFromAssertion' variable. This is a type assertion because we are telling TypeScript that we expect the result to be a number.
  • To convert a number to a string, we use the toString() method available for numbers. We assign the result to the 'stringFromAssertion' variable, again as a type assertion.
  • Finally we log the converted values to the console to verify the type conversion.

Output:

"Type of temp:",  "undefined" 
"My Variable:",  "Hello, TypeScript!"

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript type inference example.
Next: TypeScript type aliases for improved readability.

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.