This TypeScript cheat sheet covers the basics and some advanced features of TypeScript, including types, interfaces, classes, and more.
Let's get started. ;)
1. TypeScript Basics
1.1. Basic Types
- number: Represents all numbers (integers, floats).
let num: number = 42;
let str: string = "Hello, TypeScript!";
- boolean: Represents a true or false value.
let isActive: boolean = true;
- any: Represents any value. Disables type checking.
let value: any = 5;
value = "Now it's a string";
- void: Represents no value (used as the return type of functions).
function logMessage(message: string): void {
console.log(message);
}
- null and undefined: Represent the absence of a value.
let n: null = null;
let u: undefined = undefined;
let numbers: number[] = [1, 2, 3, 4];
let strings: Array<string> = ["apple", "banana", "cherry"];
1.3. Tuples
Tuples allow arrays with mixed types and fixed length.
let tuple: [string, number, boolean] = ["hello", 10, true];
1.4. Enums
Enums represent a set of named constants.
enum Direction {
Up = 1,
Down,
Left,
Right,
}
let move: Direction = Direction.Up;
1.5. Object Types
Object with specific shape:
let person: { name: string; age: number } = { name: "Alice", age: 25 };
2. Functions
2.1. Function Types
- Function with parameters and return type:
function add(a: number, b: number): number {
return a + b;
}
- Function with optional parameters:
function greet(name: string, age?: number): string {
return `Hello ${name}, you are ${age ? age : "unknown"}`;
}
function multiply(a: number, b: number = 2): number {
return a * b;
}
function sum(...nums: number[]): number {
return nums.reduce((total, num) => total + num, 0);
}
3. Interfaces
3.1. Basic Interface
interface Person {
name: string;
age: number;
}
let user: Person = { name: "Alice", age: 30 };
3.2. Optional Properties
interface Product {
id: number;
name: string;
description?: string; // Optional property
}
3.3. Readonly Properties
interface Car {
readonly make: string;
model: string;
}
const myCar: Car = { make: "Toyota", model: "Corolla" };
// myCar.make = "Honda"; // Error: cannot assign to 'make' because it is a read-only property
4. Classes
4.1. Class Declaration
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return `Hello, my name is ${this.name}`;
}
}
const person = new Person("Alice", 30);
console.log(person.greet()); // Hello, my name is Alice
4.2. Access Modifiers
- public (default): Accessible from anywhere.
- private: Only accessible within the class.
- protected: Accessible within the class and subclasses.
class Employee {
private id: number;
protected name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
getId(): number {
return this.id;
}
}
const emp = new Employee(1, "John");
// emp.id = 2; // Error: Property 'id' is private and only accessible within class 'Employee'
4.3. Inheritance
class Employee extends Person {
role: string;
constructor(name: string, age: number, role: string) {
super(name, age); // Call the parent class constructor
this.role = role;
}
greet(): string {
return `${super.greet()} and I work as a ${this.role}`;
}
}
const emp = new Employee("Alice", 30, "Developer");
console.log(emp.greet()); // Hello, my name is Alice and I work as a Developer
5. Generics
Generics provide a way to work with any data type while maintaining the integrity of types.
5.1. Generic Functions
function identity<T>(arg: T): T {
return arg;
}
let output = identity("Hello"); // T is inferred as string
let output2 = identity(100); // T is inferred as number
5.2. Generic Interfaces
interface Box<T> {
value: T;
}
let stringBox: Box<string> = { value: "Hello" };
let numberBox: Box<number> = { value: 42 };
6. Type Aliases
Type aliases allow you to create a new name for a type.
6.1. Basic Type Alias
type Point = { x: number; y: number };
let pt: Point = { x: 10, y: 20 };
6.2. Union Types
type StringOrNumber = string | number;
let value: StringOrNumber = 42;
value = "Hello"; // This is also valid
7. Type Assertions
Type assertions allow you to override TypeScript’s inferred type.
let someValue: any = "Hello, TypeScript!";
let strLength: number = (someValue as string).length; // Type assertion
8. Type Guards
Type guards narrow down the type of a variable within a conditional block.
function isString(value: any): value is string {
return typeof value === "string";
}
function example(value: string | number) {
if (isString(value)) {
console.log(value.length); // value is now narrowed to string
} else {
console.log(value.toFixed()); // value is now narrowed to number
}
}
9. Modules and Imports
9.1. Exporting Modules
// file1.ts
export const greeting = "Hello, world!";
export function greet(name: string) {
return `Hello, ${name}`;
}
9.2. Importing Modules
// file2.ts
import { greeting, greet } from './file1';
console.log(greeting); // Hello, world!
console.log(greet("Alice")); // Hello, Alice
10. Advanced Types
10.1. Intersection Types
Combines multiple types into one.
type Person = { name: string; age: number };
type Address = { city: string; country: string };
type PersonWithAddress = Person & Address;
const personWithAddress: PersonWithAddress = {
name: "Alice",
age: 30,
city: "New York",
country: "USA"
};
10.2. Conditional Types
Conditional types allow you to choose a type based on a condition.
type IsString<T> = T extends string ? "Yes" : "No";
type Test1 = IsString<string>; // "Yes"
type Test2 = IsString<number>; // "No"
11. Type Inference
TypeScript can automatically infer types when they are not explicitly defined.
let num = 10; // TypeScript infers 'num' as number
let str = "Hello"; // TypeScript infers 'str' as string
12. Conclusion
TypeScript is a powerful, statically typed superset of JavaScript that adds type safety to your code, reducing runtime errors and improving maintainability.
By using TypeScript's features like type aliases, interfaces, generics, and type inference, you can create more robust and scalable applications.
Happy Codding ;)