TypeScript
Updated: September 10, 2025Categories: Languages, Web, Backend, Frontend
Printed from:
TypeScript Cheatsheet
Language Overview
TypeScript is a statically typed superset of JavaScript that adds optional type annotations and advanced type system features. Developed by Microsoft, it compiles to plain JavaScript, enabling developers to write more robust and maintainable code for large-scale applications. TypeScript is widely used in web development, particularly with Angular, React, and Node.js ecosystems.
Basic Syntax
TypeScript
12345678910// Single line comment
/*
Multi-line comment
*/
// TypeScript-specific type annotations
let message: string = "Hello, TypeScript!";
// Compilation with type checking
console.log(message);
Data Types
Primitive Types
TypeScript
1234567891011121314151617181920212223242526272829303132333435// Number
let age: number = 25;
let pi: number = 3.14159;
// String
let name: string = "John";
let greeting: string = `Hello, ${name}!`; // Template literals
// Boolean
let isActive: boolean = true;
let isComplete: boolean = false;
// Any (opt-out of type checking)
let dynamicValue: any = 42;
dynamicValue = "string"; // Allowed
// Unknown (type-safe alternative to any)
let safeValue: unknown = 42;
// safeValue = "string"; // Allowed
// let num: number = safeValue; // Compilation error
// Void (typically used for functions)
function logMessage(): void {
console.log("No return value");
}
// Null and Undefined
let nullValue: null = null;
let undefinedValue: undefined = undefined;
// Never (represents type of values that never occur)
function throwError(): never {
throw new Error("Something failed");
}
Collection Types
TypeScript
12345678910111213141516171819202122// Array
let fruits: string[] = ["apple", "banana", "orange"];
let numbers: Array<number> = [1, 2, 3, 4, 5];
// Tuple (fixed-length array with specific types)
let coordinate: [number, number] = [10, 20];
let rgbColor: [number, number, number] = [255, 128, 0];
// Object
let person: { name: string, age: number } = {
name: "John",
age: 30
};
// Map
let userMap: Map<string, number> = new Map();
userMap.set("john", 30);
userMap.set("jane", 25);
// Set
let uniqueNumbers: Set<number> = new Set([1, 2, 3, 4, 5]);
Variables and Constants
TypeScript
12345678910111213141516171819// Variables (camelCase convention)
let userName: string = "johnDoe";
let totalCount: number = 100;
// Constants
const PI: number = 3.14159;
const MAX_SIZE: number = 1000;
const API_URL: string = "https://api.example.com";
// Type inference
let inferredNumber = 42; // TypeScript infers number
let inferredString = "Hello"; // TypeScript infers string
// Readonly properties
interface Config {
readonly apiKey: string;
readonly maxConnections: number;
}
Operators
Arithmetic Operators
TypeScript
12345678910let a: number = 10;
let b: number = 3;
console.log(a + b); // 13 (addition)
console.log(a - b); // 7 (subtraction)
console.log(a * b); // 30 (multiplication)
console.log(a / b); // 3.333... (division)
console.log(a % b); // 1 (modulus)
console.log(a ** b); // 1000 (exponentiation)
Type Operators
TypeScript
123456789101112// Typeof operator
type NumOrStr = number | string;
let value: NumOrStr = 42;
type ValueType = typeof value; // 'number'
// Instanceof operator
class Animal {}
class Dog extends Animal {}
let pet = new Dog();
console.log(pet instanceof Dog); // true
console.log(pet instanceof Animal); // true
Control Structures
TypeScript
12345678910111213141516171819202122232425262728293031// If/Else
let age: number = 20;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
// Switch with type narrowing
function processValue(value: string | number) {
switch (typeof value) {
case "string":
console.log(value.toUpperCase());
break;
case "number":
console.log(value.toFixed(2));
break;
}
}
// For loops
let items: string[] = ["a", "b", "c"];
for (let item of items) {
console.log(item);
}
// Functional iteration
items.forEach((item, index) => {
console.log(`${index}: ${item}`);
});
Functions
TypeScript
1234567891011121314151617181920// Function with type annotations
function add(a: number, b: number): number {
return a + b;
}
// Optional and default parameters
function greet(name: string, title?: string): string {
return title ? `Hello, ${title} ${name}` : `Hello, ${name}`;
}
// Arrow functions
const multiply = (a: number, b: number): number => a * b;
// Function overloading
function process(x: number): number;
function process(x: string): string;
function process(x: number | string): number | string {
return typeof x === "number" ? x * 2 : x.toUpperCase();
}
Advanced Types
Interfaces and Type Aliases
TypeScript
123456789101112131415161718// Interface
interface User {
id: number;
name: string;
email?: string; // Optional property
}
// Type Alias
type Point = {
x: number;
y: number;
};
// Extending Interfaces
interface Employee extends User {
role: string;
}
Generics
TypeScript
123456789101112131415// Generic function
function identity<T>(arg: T): T {
return arg;
}
// Generic interface
interface Container<T> {
value: T;
}
// Generic constraints
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
Enums
TypeScript
123456789101112131415// Numeric enum
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right // 3
}
// String enum
enum HttpStatus {
OK = "200",
NotFound = "404",
ServerError = "500"
}
Error Handling
TypeScript
12345678910111213141516171819// Try-catch with type
function riskyOperation(): void {
try {
throw new Error("Something went wrong");
} catch (error: unknown) {
if (error instanceof Error) {
console.error(error.message);
}
}
}
// Custom error
class ValidationError extends Error {
constructor(message: string) {
super(message);
this.name = "ValidationError";
}
}
Modules and Namespaces
TypeScript
123456789101112131415161718// Export and Import
export interface Calculator {
add(a: number, b: number): number;
}
export class BasicCalculator implements Calculator {
add(a: number, b: number): number {
return a + b;
}
}
// Namespace
namespace Utilities {
export function formatDate(date: Date): string {
return date.toISOString();
}
}
Decorators
TypeScript
123456789101112131415161718192021222324// Class decorator
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
}
// Method decorator
function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`Calling ${propertyKey}`);
return originalMethod.apply(this, args);
};
return descriptor;
}
Advanced Configuration
TypeScript
12345678910// tsconfig.json example
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true
}
}
Popular Frameworks
React with TypeScript
TypeScript
123456789101112import React, { FC, useState } from 'react';
interface Props {
name: string;
age?: number;
}
const UserProfile: FC<Props> = ({ name, age = 0 }) => {
const [count, setCount] = useState<number>(0);
return <div>{name}, {age}</div>;
};
Angular
TypeScript
1234567891011121314@Component({
selector: 'app-user',
template: '{{user.name}}'
})
export class UserComponent implements OnInit {
user: User;
constructor(private userService: UserService) {}
ngOnInit(): void {
this.user = this.userService.getUser();
}
}
Best Practices
- Always use explicit type annotations
- Prefer interfaces over type aliases for object shapes
- Use strict mode in tsconfig
- Leverage type inference
- Use union and intersection types
- Avoid
anytype - Use readonly for immutable objects
- Utilize generics for type-safe, reusable code
Resources for Further Learning
- Official TypeScript Documentation
- TypeScript Deep Dive by Basarat Ali Syed
- TypeScript Handbook
- Online Courses: Udemy, Pluralsight
- TypeScript GitHub Repository
- DefinitelyTyped (@types) for type definitions
Performance Tips
- Use type annotations to help compiler optimize
- Minimize use of
any - Use const assertions
- Leverage type narrowing
- Use built-in utility types
Testing
- Jest with ts-jest
- Mocha with ts-node
- Cypress for E2E testing
- Use @types for type-safe testing
Tooling
- Visual Studio Code
- WebStorm
- ESLint with TypeScript plugin
- Prettier for code formatting
Continue Learning
Discover more cheatsheets to boost your productivity