— No reviews yet
0 installs
16 views
0.0% view→install
Install
$ agentstack add skill-miles990-claude-software-skills-javascript-typescript ✓ scanned · ✓ verified — works with Claude Code, Cursor, and more.
Security review
✓ PassedNo issues found. Passed automated security review. · v0.1.0 How review works →
- ✓ Prompt-injection patterns
- ✓ Secret / credential exfiltration
- ✓ Dangerous shell & filesystem operations
- ✓ Untrusted network calls
- ✓ Known-malicious package signatures
What it can access
- ✓ Network access No
- ✓ Filesystem access No
- ✓ Shell / process execution No
- ● Environment & secrets Used
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
Are you the author of Javascript Typescript? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claimAbout
JavaScript & TypeScript
Overview
Modern JavaScript (ES6+) and TypeScript patterns for building robust applications.
TypeScript Fundamentals
Type Definitions
// Basic types
type UserId = string;
type Timestamp = number;
// Object types
interface User {
id: UserId;
email: string;
name: string;
createdAt: Timestamp;
metadata?: Record;
}
// Union types
type Status = 'pending' | 'active' | 'inactive';
// Discriminated unions
type Result =
| { success: true; data: T }
| { success: false; error: E };
// Generic types
interface Repository {
find(id: string): Promise;
findAll(filter?: Partial): Promise;
create(data: Omit): Promise;
update(id: string, data: Partial): Promise;
delete(id: string): Promise;
}
// Utility types
type CreateUserInput = Omit;
type UpdateUserInput = Partial>;
type UserKeys = keyof User;
// Conditional types
type Nullable = T | null;
type NonNullableFields = {
[K in keyof T]-?: NonNullable;
};
// Template literal types
type EventName = `on${Capitalize}`;
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type ApiRoute = `/${string}`;
Type Guards
// 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
// Promise creation
function delay(ms: number): Promise {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// Async/await with error handling
async function fetchUser(id: string): Promise> {
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 {
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(
items: T[],
processor: (item: T) => Promise
): Promise {
return items.reduce(async (accPromise, item) => {
const acc = await accPromise;
const result = await processor(item);
return [...acc, result];
}, Promise.resolve([] as R[]));
}
Async Iterators
// Async generator
async function* paginate(
fetcher: (page: number) => Promise
): AsyncGenerator {
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(
iterable: AsyncIterable,
fn: (item: T) => R | Promise
): AsyncGenerator {
for await (const item of iterable) {
yield await fn(item);
}
}
async function* filter(
iterable: AsyncIterable,
predicate: (item: T) => boolean | Promise
): AsyncGenerator {
for await (const item of iterable) {
if (await predicate(item)) {
yield item;
}
}
}
async function* take(
iterable: AsyncIterable,
count: number
): AsyncGenerator {
let taken = 0;
for await (const item of iterable) {
if (taken >= count) break;
yield item;
taken++;
}
}
Functional Patterns
Higher-Order Functions
// Currying
const add = (a: number) => (b: number) => a + b;
const add5 = add(5);
console.log(add5(3)); // 8
// Pipe and compose
const pipe =
(...fns: Array T>) =>
(value: T): T =>
fns.reduce((acc, fn) => fn(acc), value);
const compose =
(...fns: Array 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(
fn: (...args: Args) => Result
): (...args: Args) => Result {
const cache = new Map();
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 any>(
fn: T,
delay: number
): (...args: Parameters) => void {
let timeoutId: ReturnType;
return (...args: Parameters) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
}
// Throttle
function throttle any>(
fn: T,
limit: number
): (...args: Parameters) => void {
let inThrottle = false;
return (...args: Parameters) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
Immutable Data Patterns
// Object updates
const updateUser = (user: User, updates: Partial): User => ({
...user,
...updates,
});
// Nested updates
interface State {
users: Record;
settings: {
theme: string;
notifications: boolean;
};
}
const updateNestedState = (
state: State,
userId: string,
userUpdate: Partial
): State => ({
...state,
users: {
...state.users,
[userId]: {
...state.users[userId],
...userUpdate,
},
},
});
// Array operations (immutable)
const addItem = (arr: T[], item: T): T[] => [...arr, item];
const removeItem = (arr: T[], index: number): T[] => [
...arr.slice(0, index),
...arr.slice(index + 1),
];
const updateItem = (arr: T[], index: number, item: T): T[] => [
...arr.slice(0, index),
item,
...arr.slice(index + 1),
];
Modern JavaScript Features
Destructuring and Spread
// Object destructuring with defaults and rename
const { name, email, role = 'user', id: odentifier } = user;
// Nested destructuring
const {
address: { city, country },
} = user;
// Array destructuring
const [first, second, ...rest] = items;
const [, , third] = items; // Skip elements
// Function parameter destructuring
function createUser({
name,
email,
role = 'user',
}: {
name: string;
email: string;
role?: string;
}) {
return { id: generateId(), name, email, role };
}
// Spread for merging
const merged = { ...defaults, ...overrides };
const combined = [...arr1, ...arr2];
Optional Chaining and Nullish Coalescing
// Optional chaining
const city = user?.address?.city;
const firstItem = items?.[0];
const result = callback?.();
// Nullish coalescing (only null/undefined)
const value = input ?? defaultValue;
// Combining them
const displayName = user?.profile?.displayName ?? user?.name ?? 'Anonymous';
// Logical assignment operators
let config = { timeout: 0 };
config.timeout ||= 5000; // Assigns if falsy (won't assign, 0 is falsy)
config.timeout ??= 5000; // Assigns if null/undefined (won't assign)
config.retries ??= 3; // Assigns (undefined)
Error Handling
// Custom error classes
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
) {
super(message, 'VALIDATION_ERROR', 400);
this.name = 'ValidationError';
}
}
// Result type pattern (no exceptions)
type Result =
| { ok: true; value: T }
| { ok: false; error: E };
function ok(value: T): Result {
return { ok: true, value };
}
function err(error: E): Result {
return { ok: false, error };
}
// Using Result
function parseJSON(json: string): Result {
try {
return ok(JSON.parse(json));
} catch (e) {
return err(e as SyntaxError);
}
}
// Chaining Results
function map(result: Result, fn: (value: T) => U): Result {
return result.ok ? ok(fn(result.value)) : result;
}
function flatMap(
result: Result,
fn: (value: T) => Result
): Result {
return result.ok ? fn(result.value) : result;
}
Module Patterns
// Named exports
export const API_URL = 'https://api.example.com';
export function fetchData() {}
export class ApiClient {}
// Default export
export default class Logger {}
// Re-exports
export { UserService } from './user-service';
export { default as Logger } from './logger';
export * from './types';
export * as utils from './utils';
// Dynamic imports
async function loadModule() {
const { default: Chart } = await import('./chart');
return new Chart();
}
// Conditional imports
const adapter = await import(
process.env.NODE_ENV === 'test' ? './mock-adapter' : './real-adapter'
);
Related Skills
- [[frontend]] - React/Next.js development
- [[backend]] - Node.js server development
- [[testing]] - Jest, Vitest testing
Source & license
This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.
- Author: miles990
- Source: miles990/claude-software-skills
- License: MIT
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet — be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.