| name | javascript-typescript |
| description | Modern JavaScript and TypeScript development patterns |
| domain | programming-languages |
| version | 1.0.0 |
| tags | ["javascript","typescript","es6","nodejs","async","types"] |
| triggers | {"keywords":{"primary":["javascript","typescript","js","ts","nodejs","node","npm","deno","bun"],"secondary":["es6","async","promise","module","webpack","vite","esbuild"]},"context_boost":["web","frontend","backend","fullstack","react","vue"],"context_penalty":["python","java","csharp","rust"],"priority":"high"} |
JavaScript & TypeScript
Overview
Modern JavaScript (ES6+) and TypeScript patterns for building robust applications.
TypeScript Fundamentals
Type Definitions
type UserId = string;
type Timestamp = number;
interface User {
id: UserId;
email: string;
name: string;
createdAt: Timestamp;
metadata?: Record<string, unknown>;
}
type Status = 'pending' | 'active' | 'inactive';
type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
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>;
}
type CreateUserInput = Omit<User, 'id' | 'createdAt'>;
type UpdateUserInput = Partial<Pick<User, 'name' | 'metadata'>>;
type UserKeys = keyof User;
type Nullable<T> = T | null;
type NonNullableFields<T> = {
[K in keyof T]-?: NonNullable<T[K]>;
};
type EventName = `on${Capitalize<string>}`;
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type ApiRoute = `/${string}`;
Type Guards
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'
);
}
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();
break;
case 'cat':
animal.meow();
;
}
}
(): asserts value is {
( value !== ) {
();
}
}
(): {
();
}
Async Patterns
Promises and Async/Await
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
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 : ((error)),
};
}
}
(): <[]> {
results = .(ids.( (id)));
results
.((r): r is { : ; : } => r.)
.( r.);
}
() {
results = .(
ids.( ().( r.()))
);
results.( ({
: ids[index],
: result.,
: result. === ? result. : ,
: result. === ? result. : ,
}));
}
processSequentially<T, R>(
: T[],
: <R>
): <R[]> {
items.( (accPromise, item) => {
acc = accPromise;
result = (item);
[...acc, result];
}, .([] R[]));
}
Async Iterators
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++;
}
}
async function getAllItems() {
const items: Item[] = [];
for await (const batch of paginate(fetchPage)) {
items.push(...batch);
}
return items;
}
async function* map<T, R>(
iterable: AsyncIterable<T>,
fn: (item: T) => R | Promise<R>
): AsyncGenerator<R> {
( item iterable) {
(item);
}
}
* filter<T>(
: <T>,
: | <>
): <T> {
( item iterable) {
( (item)) {
item;
}
}
}
* take<T>(
: <T>,
:
): <T> {
taken = ;
( item iterable) {
(taken >= count) ;
item;
taken++;
}
}
Functional Patterns
Higher-Order Functions
const add = (a: number) => (b: number) => a + b;
const add5 = add(5);
console.log(add5(3));
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);
const processString = pipe(
(s: string) => s.trim(),
(s: string) => s.toLowerCase(),
s.(, )
);
memoize< [], >(
:
): {
cache = <, >();
(...: ): {
key = .(args);
(cache.(key)) {
cache.(key)!;
}
result = (...args);
cache.(key, result);
result;
};
}
debounce<T (...: []) => >(
: T,
:
): {
: < >;
{
(timeoutId);
timeoutId = ( (...args), delay);
};
}
throttle<T (...: []) => >(
: T,
:
): {
inThrottle = ;
{
(!inThrottle) {
(...args);
inThrottle = ;
( (inThrottle = ), limit);
}
};
}
Immutable Data Patterns
const updateUser = (user: User, updates: Partial<User>): User => ({
...user,
...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,
},
},
});
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, : T): T[] => [
...arr.(, index),
item,
...arr.(index + ),
];
Modern JavaScript Features
Destructuring and Spread
const { name, email, role = 'user', id: odentifier } = user;
const {
address: { city, country },
} = user;
const [first, second, ...rest] = items;
const [, , third] = items;
function createUser({
name,
email,
role = 'user',
}: {
name: string;
email: string;
role?: string;
}) {
return { id: generateId(), name, email, role };
}
const merged = { ...defaults, ...overrides };
const combined = [...arr1, ...arr2];
Optional Chaining and Nullish Coalescing
const city = user?.address?.city;
const firstItem = items?.[0];
const result = callback?.();
const value = input ?? defaultValue;
const displayName = user?.profile?.displayName ?? user?.name ?? 'Anonymous';
let config = { timeout: 0 };
config.timeout ||= 5000;
config.timeout ??= 5000;
config.retries ??= 3;
Error Handling
class AppError extends Error {
constructor(
message: string,
public code: string,
public statusCode: number = 500
) {
super(message);
this.name = 'AppError';
Error.captureStackTrace(this, this.constructor);
}
}
class ValidationError extends AppError {
constructor(
message: string,
public fields: Record<string, string[]>
) {
super(message, 'VALIDATION_ERROR', 400);
this.name = 'ValidationError';
}
}
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: ; : E };
ok<T>(: T): <T, > {
{ : , value };
}
err<E>(: E): <, E> {
{ : , error };
}
parseJSON<T>(: ): <T, > {
{
(.(json));
} (e) {
(e );
}
}
map<T, U, E>(: <T, E>, : U): <U, E> {
result. ? ((result.)) : result;
}
flatMap<T, U, E>(
: <T, E>,
: <U, E>
): <U, E> {
result. ? (result.) : result;
}
Module Patterns
export const API_URL = 'https://api.example.com';
export function fetchData() {}
export class ApiClient {}
export default class Logger {}
export { UserService } from './user-service';
export { default as Logger } from './logger';
export * from './types';
export * as utils from './utils';
async function loadModule() {
const { default: Chart } = await import('./chart');
return new Chart();
}
const adapter = await import(
process.env. === ? :
);
Related Skills
- [[frontend]] - React/Next.js development
- [[backend]] - Node.js server development
- [[testing]] - Jest, Vitest testing