Skip to content

Instantly share code, notes, and snippets.

@razhangwei
Last active August 6, 2025 12:57
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
File / Folder Purpose
src/ Source TypeScript code (.ts, .tsx)
dist/ or lib/ Compiled output (.js, .d.ts)
index.ts, main.ts Package entry point or main logic file
package.json Project metadata, scripts, dependencies
package-lock.json Dependency version lock file (auto-generated by npm)
tsconfig.json TypeScript compiler configuration (target, paths, output, etc.)
vitest.config.ts Vitest test runner configuration
test-setup.ts Global testing setup (mocks, test env setup)
README.md Project overview, instructions, and documentation
LICENSE Project licensing information
.gitignore Files/folders to exclude from Git tracking
.npmrc npm configuration (e.g., registry, auth tokens)
.editorconfig Shared editor settings for code style consistency
.eslintrc, .eslintignore ESLint configuration and ignore rules
.prettierrc, .prettierignore Prettier code formatting rules
styles.css Global or root CSS file for styling
esbuild.config.mjs Configuration for esbuild bundler
manifest.json Metadata for browser extensions or web apps (e.g., PWAs)
version-bump.mjs Custom script for automating version bumps
versions.json JSON file tracking version metadata (e.g., changelogs, multi-release)
tests/ or __tests__/ Directory for test suites
types/ Custom type declarations (.d.ts)
.env Environment variable definitions
scripts/ Custom utility or CI/CD scripts

TypeScript Cheatsheet

#typescript #cheatsheet

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

  • npm (management), npc (compile), npx (execution),
  • Node.js (runtime)

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