string, number and boolean

The Three Everyday Types

TypeValuesExample
stringtext"Ravi", 'Pune', template strings
numberall numbers: integers and decimals (64-bit float)42, 99.5, -3, NaN
booleantrue or falseisLoggedIn = true

Note: Use lowercase string, number, boolean. The capitalised String, Number, Boolean are wrapper objects and should not be used as types.

Example

Example

const productName: string = "Bluetooth Speaker";
const price: number = 1499.99;
const quantity: number = 3;
const inStock: boolean = true;

const total: number = price * quantity;
console.log(`${productName} x ${quantity} = Rs. ${total.toFixed(2)}`);
console.log("In stock:", inStock);

Output

Bluetooth Speaker x 3 = Rs. 4499.97
In stock: true

Assigning the Wrong Type

Example

Once a variable is a number, it stays a number. TypeScript reports TS2322.

let stock: number = 10;
stock = "ten";

Compiler output (tsc)

Line 2: error TS2322: Type 'string' is not assignable to type 'number'.

Practice

Exercise: Declare studentName (string), marks (number) and passed (boolean, true when marks are 35 or more). Print all three.

Show answer
const studentName: string = "Anjali";
const marks: number = 72;
const passed: boolean = marks >= 35;
console.log(studentName, marks, passed);