TypeScript ยท Chapter 5 of 44

TypeScript Basic Types

TypeScript adds type annotations to describe what kind of value a variable should hold. The most common basic types are `string`, `number`, and `boolean`, matching the primitive types already found in JavaScript.

Once a variable is annotated with a type, TypeScript will produce an error if you try to assign a value of a different type to it, catching mistakes immediately in your editor.

Syntax
let name: string = "Alice";
let age: number = 30;
let isActive: boolean = true;

string, number, boolean

`string` holds text, `number` holds any numeric value (integer or decimal), and `boolean` holds true or false. These cover most simple values in everyday code.

Type annotations

You add a type annotation with a colon after the variable name, like `let age: number = 25;`. TypeScript then enforces that type for the lifetime of the variable.

Example 1 (typescript)
let name: string = "Alice";
let age: number = 30;
let isActive: boolean = true;
console.log(name, age, isActive);
Output
Alice 30 true

Three variables are declared with explicit basic types.

Example 2 (typescript)
let score: number = 10;
// score = "high"; // Error: string is not assignable to number
score = 20;
console.log(score);
Output
20

TypeScript would reject assigning a string to a number-typed variable.

Key points

  • string, number, and boolean are the most common basic types.
  • Type annotations use a colon after the variable name.
  • Assigning the wrong type causes a compile-time error.
  • TypeScript's number type covers both integers and decimals.
๐Ÿ’ก Note: JavaScript has no separate integer type, so TypeScript's `number` represents all numeric values.

๐Ÿ“ Quick Quiz

1. Which type would you use for a person's name?

2. How do you write a type annotation for a variable?

3. What type represents true/false values?