javascript-typescript
Modern JavaScript and TypeScript development patterns
What this skill does
# JavaScript & TypeScript
## Overview
Modern JavaScript (ES6+) and TypeScript patterns for building robust applications.
---
## TypeScript Fundamentals
### Type Definitions
```typescript
// Basic types
type UserId = string;
type Timestamp = number;
// Object types
interface User {
id: UserId;
email: string;
name: string;
createdAt: Timestamp;
metadata?: Record<string, unknown>;
}
// Union types
type Status = 'pending' | 'active' | 'inactive';
// Discriminated unions
type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
// Generic types
interface Repository<T extends { id: string }> {
find(id: string): Promise<T | null>;
findAll(filter?: Partial<T>): Promise<T[]>;
create(data: Omit<T, 'id'>): Promise<T>;
update(id: string, data: Partial<T>): Promise<T>;
delete(id: string): Promise<void>;
}
// Utility types
type CreateUserInput = Omit<User, 'id' | 'createdAt'>;
type UpdateUserInput = Partial<Pick<User, 'name' | 'metadata'>>;
type UserKeys = keyof User;
// Conditional types
type Nullable<T> = T | null;
type NonNullableFields<T> = {
[K in keyof T]-?: NonNullable<T[K]>;
};
// Template literal types
type EventName = `on${Capitalize<string>}`;
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type ApiRoute = `/${string}`;
```
### Type Guards
```typescript
// Type predicates
function isUser(obj: unknown): obj is User {
return (
typeof obj === 'object' &&
obj !== null &&
'id' in obj &&
'email' in obj &&
typeof (obj as User).id === 'string'
);
}
// Discriminated union guards
interface Dog {
kind: 'dog';
bark(): void;
}
interface Cat {
kind: 'cat';
meow(): void;
}
type Animal = Dog | Cat;
function handleAnimal(animal: Animal) {
switch (animal.kind) {
case 'dog':
animal.bark(); // TypeScript knows this is Dog
break;
case 'cat':
animal.meow(); // TypeScript knows this is Cat
break;
}
}
// Assertion functions
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== 'string') {
throw new Error('Value must be a string');
}
}
// Exhaustive checks
function assertNever(x: never): never {
throw new Error(`Unexpected value: ${x}`);
}
```
---
## Async Patterns
### Promises and Async/Await
```typescript
// Promise creation
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// Async/await with error handling
async function fetchUser(id: string): Promise<Result<User>> {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
return {
success: false,
error: new Error(`HTTP ${response.status}`),
};
}
const data = await response.json();
return { success: true, data };
} catch (error) {
return {
success: false,
error: error instanceof Error ? error : new Error(String(error)),
};
}
}
// Parallel execution
async function fetchAllUsers(ids: string[]): Promise<User[]> {
const results = await Promise.all(ids.map((id) => fetchUser(id)));
return results
.filter((r): r is { success: true; data: User } => r.success)
.map((r) => r.data);
}
// Promise.allSettled for partial failures
async function fetchUsersSettled(ids: string[]) {
const results = await Promise.allSettled(
ids.map((id) => fetch(`/api/users/${id}`).then((r) => r.json()))
);
return results.map((result, index) => ({
id: ids[index],
status: result.status,
value: result.status === 'fulfilled' ? result.value : null,
error: result.status === 'rejected' ? result.reason : null,
}));
}
// Sequential execution with reduce
async function processSequentially<T, R>(
items: T[],
processor: (item: T) => Promise<R>
): Promise<R[]> {
return items.reduce(async (accPromise, item) => {
const acc = await accPromise;
const result = await processor(item);
return [...acc, result];
}, Promise.resolve([] as R[]));
}
```
### Async Iterators
```typescript
// Async generator
async function* paginate<T>(
fetcher: (page: number) => Promise<{ data: T[]; hasMore: boolean }>
): AsyncGenerator<T[], void, unknown> {
let page = 1;
let hasMore = true;
while (hasMore) {
const result = await fetcher(page);
yield result.data;
hasMore = result.hasMore;
page++;
}
}
// Using async iterator
async function getAllItems() {
const items: Item[] = [];
for await (const batch of paginate(fetchPage)) {
items.push(...batch);
}
return items;
}
// Async iterator utilities
async function* map<T, R>(
iterable: AsyncIterable<T>,
fn: (item: T) => R | Promise<R>
): AsyncGenerator<R> {
for await (const item of iterable) {
yield await fn(item);
}
}
async function* filter<T>(
iterable: AsyncIterable<T>,
predicate: (item: T) => boolean | Promise<boolean>
): AsyncGenerator<T> {
for await (const item of iterable) {
if (await predicate(item)) {
yield item;
}
}
}
async function* take<T>(
iterable: AsyncIterable<T>,
count: number
): AsyncGenerator<T> {
let taken = 0;
for await (const item of iterable) {
if (taken >= count) break;
yield item;
taken++;
}
}
```
---
## Functional Patterns
### Higher-Order Functions
```typescript
// Currying
const add = (a: number) => (b: number) => a + b;
const add5 = add(5);
console.log(add5(3)); // 8
// Pipe and compose
const pipe =
<T>(...fns: Array<(arg: T) => T>) =>
(value: T): T =>
fns.reduce((acc, fn) => fn(acc), value);
const compose =
<T>(...fns: Array<(arg: T) => T>) =>
(value: T): T =>
fns.reduceRight((acc, fn) => fn(acc), value);
// Usage
const processString = pipe(
(s: string) => s.trim(),
(s: string) => s.toLowerCase(),
(s: string) => s.replace(/\s+/g, '-')
);
// Memoization
function memoize<Args extends unknown[], Result>(
fn: (...args: Args) => Result
): (...args: Args) => Result {
const cache = new Map<string, Result>();
return (...args: Args): Result => {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key)!;
}
const result = fn(...args);
cache.set(key, result);
return result;
};
}
// Debounce
function debounce<T extends (...args: any[]) => any>(
fn: T,
delay: number
): (...args: Parameters<T>) => void {
let timeoutId: ReturnType<typeof setTimeout>;
return (...args: Parameters<T>) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
}
// Throttle
function throttle<T extends (...args: any[]) => any>(
fn: T,
limit: number
): (...args: Parameters<T>) => void {
let inThrottle = false;
return (...args: Parameters<T>) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
```
### Immutable Data Patterns
```typescript
// Object updates
const updateUser = (user: User, updates: Partial<User>): User => ({
...user,
...updates,
});
// Nested updates
interface State {
users: Record<string, User>;
settings: {
theme: string;
notifications: boolean;
};
}
const updateNestedState = (
state: State,
userId: string,
userUpdate: Partial<User>
): State => ({
...state,
users: {
...state.users,
[userId]: {
...state.users[userId],
...userUpdate,
},
},
});
// Array operations (immutable)
const addItem = <T>(arr: T[], item: T): T[] => [...arr, item];
const removeItem = <T>(arr: T[], index: number): T[] => [
...arr.slice(0, index),
...arr.slice(index + 1),
];
const updateItem = <T>(arr: T[], index: number, item: T): T[] => [
...arr.slice(0, index),
item,
...arr.slice(index + 1),
];
```
---
## Modern JavaScript Features
### Destructuring and Spread
```typescript
// Object destructuring with defaults and rename
const { name, email, role = 'user', id: odentifier } = user;
// Nested destructuring
const {
address: { city, country },
} = user;
// Array destruRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.