Skip to content

Instantly share code, notes, and snippets.

@johannschopplich
Created January 3, 2025 06:57
Show Gist options
  • Save johannschopplich/16c17063345c7f58104c60ea471274c2 to your computer and use it in GitHub Desktop.
Save johannschopplich/16c17063345c7f58104c60ea471274c2 to your computer and use it in GitHub Desktop.
TypeScript Cheat Sheet
// πŸ“œ TypeScript Cheat Sheet: Types and Their Usage
// πŸ› οΈ **Primitive Type**
// Used mostly for documentation.
type SanitizedInput = string; // Example primitive type.
type MissingNo = 404; // Custom primitive type.
// 🏠 **Object Literal Type**
type Location = {
x: number;
y: number;
};
// πŸ”Ά **Tuple Type**
// A fixed array type with specific index types.
type Data = [location: Location, timestamp: string];
// πŸ”· **Union Type**
// Describes a type that is one of many possible options.
type Size = "small" | "medium" | "large";
// ✳️ **Intersection Type**
// Combines multiple types together.
type Position = {
x: number;
} & {
y: number;
}; // { x: number, y: number }
// πŸ” **Type Indexing**
// Extracting a type from a specific property.
type Response = { data: { name: string } };
type DataType = Response["data"]; // { name: string }
// πŸ“ **Type from Value**
// Derive a type from an existing value.
const data = { name: "TypeScript" };
type DataTypeFromValue = typeof data;
// πŸ”„ **Type from Function Return**
// Get a type based on a function's return type.
const createFixtures = () => {
return { id: 1, name: "Fixture" };
};
type Fixtures = ReturnType<typeof createFixtures>;
// πŸ”„ **Mapped Types**
// Transform object types dynamically.
type Artist = { name: string; bio: string };
type Subscriber<Type> = {
[Property in keyof Type]: (value: Type[Property]) => void;
};
type ArtistSubscriber = Subscriber<Artist>;
// { name: (value: string) => void, bio: (value: string) => void }
// ❓ **Conditional Types**
// Acts as "if statements" inside the type system.
type HasFourLegs<Animal> = Animal extends { legs: 4 } ? Animal : never;
type Animals = { legs: 4; species: "Dog" } | { legs: 2; species: "Bird" };
type OnlyFourLegged = HasFourLegs<Animals>;
// { legs: 4; species: "Dog" }
// 🌐 **Template Union Types**
// Create types by combining strings.
type SupportedLangs = "en" | "pt";
type FooterIds = "header" | "footer";
type AllLocaleIDs = `${SupportedLangs}_${FooterIds}`;
// "en_header" | "en_footer" | "pt_header" | "pt_footer"
// πŸ“¦ **Object Literal Syntax**
type JSONResponse = {
version: number; // Field
payloadSize: number; // Field
outOfStock?: boolean; // Optional field
update(retryTimes: number): void; // Method
[key: string]: number; // Index signature
readonly body: string; // Readonly property
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment