Start learning free

LESSON 16 OF 675 · VARIABLES

Type Conversion in TypeScript

Lesson

In TypeScript, every value has a type: number, string, boolean, and so on. Sometimes you need to convert a value from one type to another. This is called type conversion.

Use these functions to convert between types:

String(x)      // converts x to a string
Number(x)      // converts x to a number
parseInt(x)    // converts the string x to an integer (drops decimals)
parseFloat(x)  // converts the string x to a float
Math.trunc(x)  // drops the decimals of the number x

Here are some examples:

let score = 42;
let scoreStr = String(score);        // "42"  (number → string)

let weight = 70.8;
let weightInt = Math.trunc(weight);  // 70    (float → integer, decimal dropped)

let count = "100";
let countInt = parseInt(count);      // 100   (string → integer)

Note that parseInt and Math.trunc drop the decimal part - they do not round. parseInt expects a string, so for a number use Math.trunc.

Math.trunc(9.99)  // → 9
Math.trunc(3.1)   // → 3

Assignment
Follow the Coding Tutorial and convert each variable to a different type!


Hint
Use String(), Math.trunc() and parseInt().

STEP 1 OF 3
    Ctrl + Enter to check