TypeScript Basics

Lesson 3: Variables, Data Types, and Type Inference

Understand how TypeScript handles strings, numbers, booleans, and type annotations, and how it can infer types automatically from assigned values.

Variables in TypeScript

Variables store values in a program. In TypeScript, you usually declare them with let or const.

let userName = "Alice";
const country = "Malaysia";

Type Annotations

Type annotations make the expected type explicit.

let age: number = 25;
let fullName: string = "Dr. Liew";
let isActive: boolean = true;

Common Data Types

  • string for text
  • number for integers and decimals
  • boolean for true or false
  • any for any value, though it should be used sparingly
  • unknown for values that require checking before use

Type Inference

TypeScript can often determine the type automatically from the value assigned.

let city = "Kuala Lumpur";
let year = 2026;
let published = true;

Here, TypeScript infers city as a string, year as a number, and published as a boolean.

Why Types Help

Types prevent accidental assignments and improve code readability. They also make editor suggestions smarter.

Best practice: Use explicit types when the code is not obvious, and let inference handle clear cases.

Summary

TypeScript improves ordinary JavaScript variables by allowing safer, clearer handling of data. Types reduce bugs and make programs easier to maintain.