01 / 05
A variable that holds a number is a number
Adding types
INPUT · Slides
01 / 05
numberFor a variable that holds a number, write number. Whole numbers and decimals are both number.
JavaScript has no separate "whole number type" and "decimal type", so TypeScript has none either.
const price: number = 480;const tax: number = 1.1;console.log(price * tax);Result
528.0000000000001
02 / 05
"480" and 480 are different things. The one wrapped in " is text.
Try to put "480" into a variable declared as number and TypeScript stops you. Getting these two mixed up is one of the commonest mistakes in JavaScript, and it leads to "480" + 20 quietly becoming "48020".
const price: number = "480";Result
Type error: Type 'string' is not assignable to type 'number'.
03 / 05
booleanThe type that only holds true (yes) and false (no) is boolean.
Use it for a state that is one of two things — whether someone is a member, whether something is sold out.
const isMember: boolean = true;console.log(isMember);Result
true
04 / 05
booleanWrite "true" and you have not written true, you have written the four letters t, r, u, e.
That will not go into a boolean variable. This is another place TypeScript stops you.
const isMember: boolean = "true";Result
Type error: Type 'string' is not assignable to type 'boolean'.
05 / 05
boolean tooCompare with > or === and the result is either true or false. So it is a boolean.
Which means you can put the result of a comparison straight into a boolean variable.
const score: number = 72;const passed: boolean = score >= 60;console.log(passed);Result
true