Introduction
TypeScript is a programming language built on top of JavaScript. It introduces static typing, which allows you to define the type of variables, function arguments, and return values. This makes the code easier to understand, debug, and maintain. Since TypeScript compiles down to plain JavaScript, it works anywhere JavaScript does.
Variables and Types
You can declare variables with types to avoid mistakes.
let age: number = 25;
let name: string = "Alice";
let isActive: boolean = true;
Important: TypeScript infers the type automatically if you assign a value directly.
Arrays
Define arrays with a specific type.
let numbers: number[] = [1, 2, 3];
let fruits: Array<string> = ["apple", "banana"];
Tuples
Tuples allow you to store fixed-length arrays with different types.
let person: [string, number] = ["Alice", 25];
Enums
Enums are used to define a set of named constants.
enum Direction { Up, Down, Left, Right }
let move: Direction = Direction.Up;
Any Type
any disables type checking. Use only if you are unsure of the type.
let value: any = "Hello";
value = 42;
Unknown Type
unknown is safer any because you must check the type before using it.
let input: unknown = "test";
if (typeof input === "string") {
console.log(input.toUpperCase());
}
Union Types
A variable can have more than one possible type.
let id: number | string;
id = 101;
id = "abc";
Type Aliases
You can create custom names for types.
type UserID = number | string;
let userId: UserID = 101;
Interfaces
Interfaces define the structure of objects.
interface User {
id: number;
name: string;
}
let user: User = { id: 1, name: "Alice" };
Type vs Interface
Functions
Functions can have typed parameters and return values.
function add(x: number, y: number): number {
return x + y;
}
Optional and Default Parameters
function greet(name: string, age?: number): string {
return `Hello ${name}`;
}
function multiply(a: number, b: number = 2): number {
return a * b;
}
Arrow Functions
const square = (x: number): number => x * x;
Classes
TypeScript supports object-oriented programming.
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
greet(): void {
console.log(`Hello, my name is ${this.name}`);
}
}
let p = new Person("Alice");
p.greet();
Access Modifiers
public (default): accessible everywhere
private : accessible only inside the class
protected : accessible inside class and subclasses
class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
}
Readonly Properties
class Car {
readonly model: string;
constructor(model: string) {
this.model = model;
}
}
Generics
Generics allow functions and classes to work with different data types.
function identity<T>(value: T): T {
return value;
}
let output = identity<string>("Hello");
Type Assertions
Tell the compiler to treat a value as a specific type.
let someValue: unknown = "Hello";
let strLength: number = (someValue as string).length;
Null and Undefined
Use strict null checks to avoid errors.
let x: string | null = null;
Never Type
Represents a function that never returns.
function error(message: string): never {
throw new Error(message);
}
Modules and Imports
You can split code into modules.
// file: math.ts
export function add(x: number, y: number) {
return x + y;
}
// file: app.ts
import { add } from "./math";
console.log(add(2, 3));
Type Narrowing
You can narrow down union types with checks.
function printId(id: number | string) {
if (typeof id === "string") {
console.log(id.toUpperCase());
} else {
console.log(id);
}
}
Utility Types
TypeScript provides built-in helper types.
Partial<T> : makes all properties optional
Required<T> : makes all properties required
Readonly<T> : makes all properties read-only
Pick<T, K> : picks specific properties
Omit<T, K> : removes specific properties
interface User {
id: number;
name: string;
age: number;
}
type PartialUser = Partial<User>;
Conclusion
TypeScript enhances JavaScript development by introducing types, interfaces, and advanced features such as generics and utility types, making it more reliable and structured. With this cheatsheet, you have a quick reference to the most critical parts of TypeScript. By using TypeScript effectively, you can write cleaner code, catch errors early, and build large applications with more confidence.