Community Wiki & Forum
Frontend Development
January 2024
42 active contributors
Type-safe JavaScript patterns and advanced techniques
TypeScript provides built-in utility types to transform existing types into new types.
// Partial - Make all properties optional
interface User {
id: string;
name: string;
email: string;
}
type PartialUser = Partial<User>;
// { id?: string; name?: string; email?: string; }
// Pick - Select specific properties
type UserPreview = Pick<User, 'id' | 'name'>;
// { id: string; name: string; }
// Omit - Exclude specific properties
type UserWithoutEmail = Omit<User, 'email'>;
// { id: string; name: string; }
// Record - Create object type with specific keys
type UserRoles = Record<string, 'admin' | 'user' | 'guest'>;
// { [key: string]: 'admin' | 'user' | 'guest' }
// ReturnType - Extract return type of function
function getUser() {
return { id: '1', name: 'John' };
}
type User = ReturnType<typeof getUser>;Use generics to create reusable, type-safe components and functions.
// Generic function
function identity<T>(value: T): T {
return value;
}
// Generic interface
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
// Generic React component
interface ListProps<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
}
function List<T>({ items, renderItem }: ListProps<T>) {
return <div>{items.map(renderItem)}</div>;
}
// Usage
<List<User>
items={users}
renderItem={(user) => <div>{user.name}</div>}
/>
// Generic constraints
interface HasId {
id: string;
}
function findById<T extends HasId>(items: T[], id: string): T | undefined {
return items.find(item => item.id === id);
}Create type guards to narrow down types and ensure type safety at runtime.
// typeof type guard
function isString(value: unknown): value is string {
return typeof value === 'string';
}
// instanceof type guard
class Dog {
bark() { console.log('Woof!'); }
}
function isDog(animal: unknown): animal is Dog {
return animal instanceof Dog;
}
// Custom type guard
interface Cat {
meow(): void;
}
function isCat(animal: unknown): animal is Cat {
return (animal as Cat).meow !== undefined;
}
// Discriminated unions
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; size: number };
function getArea(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'square':
return shape.size ** 2;
}
}No comments yet. Be the first to join the discussion!