| name | typescript-expert |
| description | Advanced TypeScript patterns and best practices |
| triggers | ["context","typescript","types","generics"] |
TypeScript Expert Skill
Purpose: Apply advanced TypeScript patterns for type-safe code
Overview
This skill provides advanced TypeScript techniques for building robust, type-safe applications.
Utility Types
Built-in Utilities
type UpdateUser = Partial<User>;
type CompleteUser = Required<User>;
type UserCredentials = Pick<User, "email" | "password">;
type PublicUser = Omit<User, "password" | "hashedToken">;
type UserRoles = Record<string, Role>;
Generics
Basic Generic
function identity<T>(value: T): T {
return value;
}
Constrained Generic
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
Generic Class
class Repository<T extends { id: string }> {
async findById(id: string): Promise<T | null> { ... }
async save(entity: T): Promise<T> { ... }
}
Type Guards
typeof Guard
function process(value: string | number) {
if (typeof value === "string") {
return value.toUpperCase();
}
return value * 2;
}
instanceof Guard
function handleError(error: Error | string) {
if (error instanceof ValidationError) {
return { code: "VALIDATION", message: error.message };
}
return { code: "UNKNOWN", message: String(error) };
}
Custom Guard
interface User {
type: "user";
name: string;
}
interface Admin {
type: "admin";
name: string;
permissions: string[];
}
function isAdmin(person: User | Admin): person is Admin {
return person.type === "admin";
}
Discriminated Unions
type Result<T> = { success: true; data: T } | { success: false; error: string };
function handleResult<T>(result: Result<T>) {
if (result.success) {
console.log(result.data);
} else {
console.error(result.error);
}
}
Mapped Types
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
type Optional<T> = {
[P in keyof T]?: T[P];
};
type Nullable<T> = {
[P in keyof T]: T[P] | null;
};
Quick Reference
| Pattern | Usage |
|---|
Partial<T> | Optional updates |
Required<T> | Strict validation |
Pick<T, K> | Select properties |
Omit<T, K> | Exclude properties |
Record<K, V> | Key-value maps |
Extract<T, U> | Filter union types |
Exclude<T, U> | Exclude union types |
NonNullable<T> | Remove null/undefined |