TypeScript Snippets
Type-safe JavaScript code snippets and patterns
Type Interfaces
typescriptDefine custom types using interfaces
interface User {
id: number;
name: string;
email: string;
age?: number; // Optional property
}
const user: User = {
id: 1,
name: 'John',
email: 'john@example.com'
};Generic Functions
typescriptCreate reusable generic functions
function getFirstElement<T>(arr: T[]): T | undefined {
return arr[0];
}
// Usage
const numbers = [1, 2, 3];
const firstNum = getFirstElement(numbers); // Type: number
const strings = ['a', 'b', 'c'];
const firstStr = getFirstElement(strings); // Type: stringUnion Types
typescriptCombine multiple types using unions
type Status = 'pending' | 'success' | 'error';
interface ApiResponse {
status: Status;
data: string | null;
error?: string;
}
function handleResponse(response: ApiResponse) {
switch (response.status) {
case 'success':
console.log(response.data);
break;
case 'error':
console.error(response.error);
break;
}
}Type Guards
typescriptUse type guards for runtime type checking
interface Bird {
type: 'bird';
flySpeed: number;
}
interface Horse {
type: 'horse';
runSpeed: number;
}
type Animal = Bird | Horse;
function moveAnimal(animal: Animal) {
if (animal.type === 'bird') {
console.log(`Flying at ${animal.flySpeed}km/h`);
} else {
console.log(`Running at ${animal.runSpeed}km/h`);
}
}