Here’s a TypeScript Cheat Sheet covering the essential syntax, types, and features of TypeScript. This guide is useful for developers transitioning from JavaScript to TypeScript or looking for a quick reference. It includes type annotations, interfaces, classes, generics, and more.
Basic Syntax
Type Annotations
let name: string = "Alice";
let age: number = 25;
let isActive: boolean = true;
Arrays and Tuples
let numbers: number[] = [1, 2, 3];
let user: [string, number] = ["Alice", 25]; // Tuple
Functions
function add(a: number, b: number): number {
return a + b;
}
Optional and Default Parameters
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
function logMessage(message?: string): void {
console.log(message || "No message");
}
Object and Interface
Defining an Interface
interface User {
name: string;
age: number;
isAdmin?: boolean; // Optional property
}
const user: User = { name: "Alice", age: 25 };
Type vs. Interface
- Interface: Used for defining object structure, can be extended.
- Type: More flexible, can be used for unions, intersections, etc.
type Point = { x: number; y: number };
interface Person { name: string; age: number; }
Classes and Inheritance
Defining a Class
class Person {
constructor(public name: string, private age: number) {}
greet(): string {
return `Hello, my name is ${this.name}.`;
}
}
Extending a Class
class Employee extends Person {
constructor(name: string, age: number, public role: string) {
super(name, age);
}
}
Implementing an Interface
interface Animal {
name: string;
makeSound(): void;
}
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound() {
console.log("Woof!");
}
}
Advanced Types
Union and Intersection Types
let value: string | number = "Hello"; // Union
type Admin = { privileges: string[] };
type Employee = { name: string };
type AdminEmployee = Admin & Employee; // Intersection
Type Assertions
let someValue: any = "Hello, TypeScript!";
let strLength: number = (someValue as string).length;
Generics
Generic Functions
function identity<T>(value: T): T {
return value;
}
let output = identity<string>("Hello");
Generic Classes
class Box<T> {
content: T;
constructor(content: T) {
this.content = content;
}
}
let numberBox = new Box<number>(100);
Utility Types
Partial, Readonly, Pick, Omit
interface Person {
name: string;
age: number;
address?: string;
}
let partialPerson: Partial<Person> = { name: "Alice" };
let readonlyPerson: Readonly<Person> = { name: "Bob", age: 30 };
type PersonName = Pick<Person, "name">; // { name: string }
type PersonWithoutAge = Omit<Person, "age">; // { name: string, address?: string }
Record and Required
type UserRoles = "admin" | "user" | "editor";
let roles: Record<UserRoles, string> = { admin: "Admin", user: "User", editor: "Editor" };
let requiredPerson: Required<Person> = { name: "Alice", age: 30, address: "NY" };
TypeScript in Practice
Working with Enums
enum Role {
Admin = "ADMIN",
User = "USER",
}
let userRole: Role = Role.Admin;
Using never
for Exhaustiveness Checking
function handleCase(value: "a" | "b"): void {
switch (value) {
case "a":
console.log("A");
break;
case "b":
console.log("B");
break;
default:
const exhaustiveCheck: never = value;
}
}
Tips and Sources
Useful Tips
- Use strict mode (
"strict": true
intsconfig.json
) for safer type checking. - Prefer interfaces for object types and types for unions or mapped types.
- Use generics for reusable functions and classes.
- Leverage utility types (
Partial
,Readonly
,Pick
, etc.) to manipulate types dynamically.