What type conversion is
Every value has a type, such as number, string or boolean. Type conversion means producing a new value of a different type from an existing one: the number 25 becomes the string "25", or the string "2024" becomes the number 2024. You need it whenever data arrives in one form and you want to use it in another, for example text typed by a user that you want to do arithmetic on.
One point matters more than any function: TypeScript's types exist only while the compiler checks your code. They are erased when the code is compiled to JavaScript, so a type annotation never converts anything. Writing const n: number = "5" is reported as a type error, and a cast such as raw as number only tells the compiler to trust you. To really change a value at run time, you call a function.
The conversion functions
These are the tools the lesson uses:
String(x)returns the text form of any value.Number(x)converts a string (or another value) to a number, and givesNaNif it can't.parseInt(text)reads an integer from the start of a string and stops at the first character that doesn't belong.parseFloat(text)does the same for numbers with a decimal part.Math.trunc(n)removes the fractional part of a number.
Here they are on small examples, with the output I got from running them:
const age: number = 25;
const ageStr: string = String(age);
console.log(ageStr, typeof ageStr); // 25 string
const year: string = "2024";
const yearInt: number = parseInt(year);
console.log(yearInt, typeof yearInt); // 2024 number
console.log(parseFloat("3.9abc")); // 3.9
console.log(String(true), String(null)); // true null
Converting a number to an integer
JavaScript's parseInt is a function for strings. Its parameter is typed as a string, so parseInt(9.99) is a type error that the compiler reports ("Argument of type 'number' is not assignable to parameter of type 'string'"). The JavaScript that tsc still writes happens to run and prints 9, because parseInt turns its argument into text first, but the error is a sign that the code does not say what you mean. A number in TypeScript is always a floating-point value, and there is no separate integer type. To "turn it into an integer" you remove the fraction, and Math.trunc does exactly that:
const price: number = 9.99;
console.log(Math.trunc(price)); // 9
console.log(Math.round(price)); // 10
console.log(Math.trunc(-9.99)); // -9
console.log(Math.floor(-9.99)); // -10
Note the difference between the functions. Math.trunc drops the decimals, so 9.99 becomes 9, not 10. Math.round goes to the nearest integer. For negative numbers, Math.trunc moves toward zero while Math.floor moves down, which is why they disagree on -9.99. The result is still a number: the value 9 is typed the same as 9.99.
Gotchas
- Casts don't convert. If a value of type
anyholds the string"5", thenraw as numberstill holds a string at run time. Adding 1 gives"51", not 6, because+joins strings. UseNumber(raw). parseIntis forgiving,Numberis strict.parseInt("42px")gives 42, whileNumber("42px")givesNaN. An empty string behaves differently again:Number("")is 0 butparseInt("")isNaN.NaNis a number.parseInt("abc")returnsNaN, whose type isnumber, so the compiler can't warn you. Check withNumber.isNaNwhen the input is untrusted.- Non-decimal text.
parseInt("ff", 16)reads hexadecimal and gives 255. Passing the base explicitly avoids surprises, sinceparseInt("0x1f")is read as hexadecimal without being asked.
The exercise, step by step
The starter code declares three constants:
const age: number = 25;
const price: number = 9.99;
const year: string = "2024";
You add a converted version of each one underneath, with the type that fits the result.
ageStr. The source is a number and the target is a string, soString(age)is the right call. The annotation isstring.priceInt. The source is already a number, so the job is to remove the fraction.Math.trunc(price)gives 9. The annotation staysnumber, andparseIntwould be reported as a type error here.yearInt. The source is a string of digits, which is whatparseIntexpects.parseInt(year)gives the number 2024.
The complete solution:
const age: number = 25;
const price: number = 9.99;
const year: string = "2024";
const ageStr: string = String(age);
const priceInt: number = Math.trunc(price);
const yearInt: number = parseInt(year);
Nothing is printed, because the lesson only asks for the three declarations. Add a console.log of each one if you want to see the values: 25, 9 and 2024, with the first one being text.
Key takeaways
- Annotations and
ascasts are erased at compile time and convert nothing. Functions convert. - Use
String(x)for number to string, andparseInt,parseFloatorNumberfor string to number. - To drop the decimals of a number, use
Math.trunc. It truncates; it does not round. - A failed conversion gives
NaN, not an error.