TypeScript
2 min read
Updated 11 Aug 2026
TypeScript Cheat Sheet
A quick reference guide for common TypeScript syntax and features.
🧑🏫 Sabse pehle — simple mein samjho#
Ye ek quick reference page hai jab tum fast code kar rahe ho aur kisi syntax ko yaad na kar pa rahe ho. Ise bookmark karke rakho!
1. Basic Types#
let str: string = "Hello";
let num: number = 42;
let isTrue: boolean = true;
let arr: string[] = ["A", "B"]; // or Array<string>
let tuple: [string, number] = ["Id", 1];
let anything: any = "Danger";
let dunno: unknown = "Better than any";
2. Interfaces & Types#
// Interface (Extendable)
interface Person {
name: string;
age?: number; // Optional
readonly id: string; // Cannot be reassigned
}
interface Employee extends Person {
salary: number;
}
// Type (Great for Unions/Primitives)
type Status = "Pending" | "Done"; // Union
type ID = string | number;
type Worker = Person & { shift: string }; // Intersection
3. Functions#
// Arrow Function
const add = (a: number, b: number): number => a + b;
// Default & Optional params
function greet(name: string, greeting: string = "Hi", title?: string) {}
// Function Types (Signature)
type OnClickFunc = (e: React.MouseEvent<HTMLButtonElement>) => void;
4. Arrays & Objects (Record)#
// Dictionary / Map
const config: Record<string, string> = {
theme: "dark",
lang: "en",
};
5. Utility Types (Quick Modifiers)#
interface Todo { title: string; desc: string; }
// Make all optional: { title?: string; desc?: string }
type PartialTodo = Partial<Todo>;
// Make all readonly: { readonly title: string; readonly desc: string }
type ReadonlyTodo = Readonly<Todo>;
// Pick specific fields: { title: string }
type TodoPreview = Pick<Todo, "title">;
// Omit specific fields: { desc: string }
type TodoDesc = Omit<Todo, "title">;
6. React Types (Commonly Used)#
import React, { useState, useRef } from "react";
// Props
type Props = { children: React.ReactNode; text: string };
// FC Component (Modern Way without React.FC)
export default function MyComponent({ children, text }: Props) {
// useState with explicit type
const [user, setUser] = useState<User | null>(null);
// useRef for DOM elements
const inputRef = useRef<HTMLInputElement>(null);
// Events
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {}
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {}
return <div onClick={handleClick}>{text}</div>
}
7. Enums vs Union Types#
// Enums (Compiles directly to a JS Object)
enum Color { Red = "RED", Blue = "BLUE" }
// Literal Unions (Lighter weight, highly preferred in React)
type ColorUnion = "RED" | "BLUE";
8. Type Guards (Narrowing)#
// Using typeof
if (typeof val === "string") { /* string methods are safe here */ }
// Using 'in' for objects
if ("email" in userObj) { /* accessing email is safe here */ }
// Custom type guard
function isString(val: any): val is string {
return typeof val === "string";
}