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.
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://www.w3resource.com/typescript-exercises/typescript-basic-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics