Skip to content

Instantly share code, notes, and snippets.

@razhangwei
Last active June 12, 2025 09:04
Show Gist options
  • Save razhangwei/96828a46f1c3989413fb04c49d06ad3e to your computer and use it in GitHub Desktop.
Save razhangwei/96828a46f1c3989413fb04c49d06ad3e to your computer and use it in GitHub Desktop.
TypeScript Cheatsheet

TypeScript Cheatsheet

#typescript #cheatsheet

A strongly-typed superset of JavaScript. TypeScript adds static typing, modern JS features, and great tooling for large-scale applications.


1. Basic Types

let name: string = "John";
let age: number = 30;
let isActive: boolean = true;
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 42]; // Fixed-type array
enum Color { Red = "RED", Green = "GREEN" };
let notSure: any = "could be anything";
let nothing: void = undefined; // Used for function returns

2. Interfaces

interface User {
  id: number;
  name: string;
  email?: string; // Optional
}
const user: User = { id: 1, name: "Alice" };

3. Functions

function add(a: number, b: number): number {
  return a + b;
}
function greet(name: string, greeting: string = "Hello"): string {
  return `${greeting}, ${name}!`;
}
// Async/await
async function fetchData(): Promise<Data> {
  const response = await fetch('/api');
  return response.json();
}

4. Classes

class Person {
  private age: number;
  constructor(public name: string, age: number) {
    this.age = age;
  }
  describe(): string {
    return `${this.name} is ${this.age} years old.`;
  }
}
class Employee extends Person {
  constructor(name: string, age: number, public role: string) {
    super(name, age);
  }
}

5. Generics

function identity<T>(arg: T): T {
  return arg;
}
interface ApiResponse<T> {
  data: T;
  status: number;
}
const response: ApiResponse<User> = { data: user, status: 200 };

6. Unions & Intersections

type StringOrNumber = string | number; // Union
type Combined = User & { permissions: string[] }; // Intersection

7. Type Guards

if (typeof value === "string") { /* ... */ }
if (value instanceof User) { /* ... */ }
// Custom type guard
function isString(x: unknown): x is string {
  return typeof x === 'string';
}

8. Advanced Types

// Type Aliases
type Point = { x: number; y: number };
// Utility Types
type PartialUser = Partial<User>;
type NameOnly = Pick<User, 'name'>;
type PermissionMap = Record<string, boolean>;
type ReadonlyUser = Readonly<User>;
// Structural Typing (Duck Typing)
interface A { name: string }
const obj = { name: 'test', extra: true };
const a: A = obj; // OK

9. Modules and Imports

import { Route } from '@/types';
import got from '@/utils/got';
import { getApiUrl, parseArticle } from './common';

10. Async/Await & Promises

async function handler(ctx): Promise<Output> {
  const data = await got({ method: 'get', url: '/api' });
  return process(data);
}
// Parallel async
const items = await Promise.all([fn1(), fn2()]);

11. Working with URL and searchParams

const apiUrl = new URL('/endpoint', 'https://example.com');
apiUrl.searchParams.append('key', 'value');

12. Object Destructuring & Access

const { data } = response;
const attributes = item.attributes;

13. Typing Function Parameters & Objects

async function handler(ctx: Context): Promise<Output> { /*...*/ }

14. Compilation

tsc file.ts # Compiles to file.js

Project config:

{
  "compilerOptions": {
    "target": "ES6",
    "strict": true
  }
}

15. Full Example: Async, Imports, Structural Typing

import got from 'got';

interface Article {
  id: number;
  title: string;
}

async function fetchArticles(): Promise<Article[]> {
  const url = new URL('/articles', 'https://example.com');
  url.searchParams.append('sort', '-date');
  const response = await got({ method: 'get', url: url.toString() });
  return response.body.data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment