typescript-expert
Advanced TypeScript: generics, conditional types, mapped types, type guards, utility types, and strict type safety patterns.
What this skill does
# TypeScript Expert
Advanced type-level programming for robust, self-documenting code.
## Generics
```typescript
// Constrained generic
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
// Generic with default
type ApiResponse<T = unknown> = { data: T; status: number; error?: string };
// Generic class
class Repository<T extends { id: string }> {
private items = new Map<string, T>();
save(item: T) { this.items.set(item.id, item); }
find(id: string): T | undefined { return this.items.get(id); }
}
```
## Conditional Types
```typescript
// Extract return type based on input
type ApiResult<T> = T extends 'user' ? User : T extends 'post' ? Post : never;
// Infer nested types
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
type Result = UnwrapPromise<Promise<string>>; // string
// Distributive conditional
type NonNullable<T> = T extends null | undefined ? never : T;
```
## Mapped Types
```typescript
// Make all properties optional
type Partial<T> = { [K in keyof T]?: T[K] };
// Make all properties readonly
type Readonly<T> = { readonly [K in keyof T]: T[K] };
// Remap keys
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };
// { getName: () => string; getAge: () => number }
```
## Type Guards
```typescript
// Custom type guard
function isUser(value: unknown): value is User {
return typeof value === 'object' && value !== null && 'email' in value;
}
// Discriminated union
type Result<T> = { ok: true; data: T } | { ok: false; error: string };
function handle<T>(result: Result<T>) {
if (result.ok) {
console.log(result.data); // TypeScript knows data exists
} else {
console.log(result.error); // TypeScript knows error exists
}
}
// Assertion function
function assertDefined<T>(value: T | undefined, msg: string): asserts value is T {
if (value === undefined) throw new Error(msg);
}
```
## Utility Types
```typescript
// Pick specific properties
type UserPreview = Pick<User, 'id' | 'name'>;
// Omit properties
type CreateUserInput = Omit<User, 'id' | 'createdAt'>;
// Required
type StrictConfig = Required<Config>;
// Record
type UserMap = Record<string, User>;
// Extract from union
type StringOrNumber = Extract<string | number | boolean, string | number>;
// Parameters and ReturnType
type FnParams = Parameters<typeof myFunction>;
type FnReturn = ReturnType<typeof myFunction>;
```
## Template Literal Types
```typescript
type EventName = `on${Capitalize<'click' | 'hover' | 'focus'>}`;
// "onClick" | "onHover" | "onFocus"
type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type Endpoint = `/${string}`;
type Route = `${HTTPMethod} ${Endpoint}`;
```
## Strict Patterns
```typescript
// Exhaustive switch
function assertNever(x: never): never {
throw new Error(`Unexpected value: ${x}`);
}
type Status = 'active' | 'inactive' | 'pending';
function handleStatus(status: Status) {
switch (status) {
case 'active': return 'green';
case 'inactive': return 'red';
case 'pending': return 'yellow';
default: return assertNever(status); // Compile error if case missed
}
}
// Branded types (prevent mixing IDs)
type UserId = string & { __brand: 'UserId' };
type PostId = string & { __brand: 'PostId' };
function getUser(id: UserId) { /* ... */ }
// getUser(postId) → compile error
```
## tsconfig Strict Settings
```json
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true
}
}
```
## Notes
- `unknown` over `any` — forces type checking before use.
- Prefer discriminated unions over optional properties for state modeling.
- `as const` makes literal types: `const x = [1, 2] as const` → `readonly [1, 2]`.
- Avoid type assertions (`as`). If you need one, you probably need a type guard instead.
- Use `satisfies` to validate without widening: `const config = {...} satisfies Config`.
Related 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.