Adding types

INPUT · Slides

The number and boolean types

01 / 05

A variable that holds a number is a number

For 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

Do not be fooled by how a number looks

"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

Yes or no is a boolean

The 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

Text does not fit in a boolean

Write "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

The result of a comparison is a boolean too

Compare 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