function isCat(pet: Cat | Dog): pet is Cat {
return (pet as Cat).meow !== undefined;
}
function createUserId(id: string): UserId {
return id as UserId;
}
Prevent mixing similar primitive types
function parseJson<T>(json: string): Result<T> {
try {
return { success: true, data: JSON.parse(json) };
} catch (e) {
return { success: false, error: e as Error };
}
}
const successful = results
.filter((r): r is PromiseFulfilledResult<User> => r.status === "fulfilled")
.map((r) => r.value);
for await (const item of paginate(fetchUsers)) {
console.log(item);
}
// Default export
export default class Service {}
// Re-exports
export { util } from "./util.js";
export type { UtilOptions } from "./util.js";
export default tseslint.config(
eslint.configs.recommended,
...tseslint.configs.strictTypeChecked,
{
languageOptions: {
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
}
);
import.meta.dirname requires Node.js 20.11+ or 21.2+ (not available in Node.js 18 LTS)
Prettier configuration for TypeScript
{
"semi": true,
"singleQuote": false,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100
}
export default defineConfig({
test: {
globals: true,
environment: "node",
coverage: {
provider: "v8",
reporter: ["text", "json", "html"],
},
},
});
const config: Config = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["<rootDir>/src"],
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
},
};
export default config;
export default defineConfig({
entry: ["src/index.ts"],
format: ["cjs", "esm"],
dts: true,
clean: true,
sourcemap: true,
});
type Status = (typeof Status)[keyof typeof Status];
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: typescript-ecosystem3description: This skill should be used when the user asks to "write typescript", "typescript config", "tsconfig", "type definition", "generics", "utility types", or works with TypeScript language patterns and configuration. Provides comprehensive TypeScript ecosystem patterns and best practices. Use when this capability is needed.4---56<purpose>7Provide comprehensive patterns for TypeScript language, configuration, type system, and tooling integration.8</purpose>910<tsconfig>11<recommended_base>12<description>Node.js version-specific recommended configurations</description>13<mapping>14<version node="22" lts="true" target="ES2023">Current LTS - use ES2023 for stable features</version>15<version node="24" upcoming="true" target="ES2024">Upcoming - use ES2024 for latest features</version>16</mapping>17<version node="22" lts="true">18<config>19{20 "compilerOptions": {21 "target": "ES2023",22 "lib": ["ES2023"],23 "module": "nodenext",24 "moduleResolution": "nodenext",25 "strict": true,26 "esModuleInterop": true,27 "skipLibCheck": true,28 "declaration": true,29 "declarationMap": true,30 "sourceMap": true,31 "outDir": "./dist",32 "rootDir": "./src"33 },34 "include": ["src"],35 "exclude": ["node_modules", "dist"]36}37</config>38<note>Node.js 22 LTS - use ES2023 target/lib for stable features</note>39</version>40<version node="24" upcoming="true">41<config>42{43 "compilerOptions": {44 "target": "ES2024",45 "lib": ["ES2024"],46 "module": "nodenext",47 "moduleResolution": "nodenext",48 "strict": true,49 "esModuleInterop": true,50 "skipLibCheck": true,51 "declaration": true,52 "declarationMap": true,53 "sourceMap": true,54 "outDir": "./dist",55 "rootDir": "./src"56 },57 "include": ["src"],58 "exclude": ["node_modules", "dist"]59}60</config>61<note>Node.js 24 (upcoming) - use ES2024 target/lib for latest features</note>62</version>63</recommended_base>6465<strict_options>6667<option name="strict">Enables all strict type-checking options</option>68<option name="strictNullChecks">null and undefined handled explicitly</option>69<option name="strictFunctionTypes">Stricter function type checking</option>70<option name="strictBindCallApply">Check bind, call, apply methods</option>71<option name="strictPropertyInitialization">Class properties must be initialized</option>72<option name="noImplicitAny">Error on implicit any types</option>73<option name="noImplicitReturns">Error on missing return statements</option>74<option name="noImplicitThis">Error on implicit this</option>75<option name="noUncheckedIndexedAccess">Add undefined to index signatures</option>76<option name="noUnusedLocals">Error on unused local variables</option>77<option name="noUnusedParameters">Error on unused parameters</option>78</strict_options>7980<module_resolution>81<pattern name="nodenext">82<description>Modern Node.js ESM resolution (recommended)</description>83<example>84{85"compilerOptions": {86"module": "nodenext",87"moduleResolution": "nodenext"88}89}90</example>91<note>Requires "type": "module" in package.json</note>92</pattern>9394<pattern name="bundler">95<description>For projects using bundlers (Vite, esbuild, webpack)</description>96<example>97{98 "compilerOptions": {99 "module": "esnext",100 "moduleResolution": "bundler"101 }102}103</example>104</pattern>105106<pattern name="path_aliases">107<description>Import path aliases</description>108<example>109{110 "compilerOptions": {111 "baseUrl": ".",112 "paths": {113 "@/*": ["src/*"],114 "@components/*": ["src/components/*"]115 }116 }117}118</example>119<warning>baseUrl: deprecated in TS 6.0, removed in TS 7.0; prefer paths without baseUrl</warning>120<warning>moduleResolution: "node" (alias "node10"): deprecated in TS 5.x; use "nodenext" or "bundler"</warning>121</pattern>122</module_resolution>123124<project_references>125<description>Monorepo and incremental builds</description>126<example>127{128"compilerOptions": {129"composite": true,130"incremental": true,131"tsBuildInfoFile": ".tsbuildinfo"132},133"references": [134{ "path": "../shared" },135{ "path": "../core" }136]137}138</example>139<note>Use tsc --build for incremental compilation</note>140</project_references>141</tsconfig>142143<type_patterns>144<utility_types>145<type name="Partial<T>">Make all properties optional</type>146<type name="Required<T>">Make all properties required</type>147<type name="Readonly<T>">Make all properties readonly</type>148<type name="Record<K,V>">Object type with key K and value V</type>149<type name="Pick<T,K>">Select specific properties from T</type>150<type name="Omit<T,K>">Exclude specific properties from T</type>151<type name="Exclude<T,U>">Exclude types from union</type>152<type name="Extract<T,U>">Extract types from union</type>153<type name="NonNullable<T>">Remove null and undefined</type>154<type name="ReturnType<T>">Get function return type</type>155<type name="Parameters<T>">Get function parameter types as tuple</type>156<type name="Awaited<T>">Unwrap Promise type</type>157</utility_types>158159<generics>160<pattern name="basic">161<description>Basic generic function</description>162<example>163function identity<T>(arg: T): T {164 return arg;165}166</example>167</pattern>168169<pattern name="constraints">170<description>Generic with type constraints</description>171<example>172function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {173 return obj[key];174}175</example>176</pattern>177178<pattern name="default_type">179<description>Generic with default type parameter</description>180<example>181interface Container<T = string> {182 value: T;183}184</example>185</pattern>186187<pattern name="multiple_constraints">188<description>Multiple generic parameters with constraints</description>189<example>190function merge<T extends object, U extends object>(a: T, b: U): T & U {191 return { ...a, ...b };192}193</example>194</pattern>195</generics>196197<conditional_types>198<pattern name="basic">199<description>Basic conditional type</description>200<example>201type IsString<T> = T extends string ? true : false;202</example>203</pattern>204205<pattern name="infer">206<description>Extract types within conditional</description>207<example>208type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;209type ArrayElement<T> = T extends (infer E)[] ? E : never;210</example>211</pattern>212213<pattern name="distributive">214<description>Distributes over union types</description>215<example>216type ToArray<T> = T extends any ? T[] : never;217// ToArray<string | number> = string[] | number[]218</example>219</pattern>220</conditional_types>221222<mapped_types>223<pattern name="basic">224<description>Basic mapped type</description>225<example>226type Readonly<T> = {227readonly [P in keyof T]: T[P];228};229</example>230</pattern>231232<pattern name="key_remapping">233<description>Map keys with renaming</description>234<example>235type Getters<T> = {236 [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];237};238</example>239</pattern>240241<pattern name="filtering">242<description>Filter properties by type</description>243<example>244type OnlyStrings<T> = {245 [K in keyof T as T[K] extends string ? K : never]: T[K];246};247</example>248</pattern>249</mapped_types>250251<template_literal_types>252<pattern name="basic">253<description>Template literal type construction</description>254<example>255type EventName = `on${Capitalize<string>}`;256type Locale = `${Language}-${Country}`;257</example>258</pattern>259260<pattern name="inference">261<description>Extract parameters from template literals</description>262<example>263type ExtractRouteParams<T> = T extends `${string}:${infer Param}/${infer Rest}`264 ? Param | ExtractRouteParams<Rest>265 : T extends `${string}:${infer Param}`266 ? Param267 : never;268</example>269</pattern>270</template_literal_types>271272<type_guards>273<pattern name="typeof">274<description>Built-in typeof type guard</description>275<example>276function process(value: string | number) {277if (typeof value === "string") {278return value.toUpperCase();279}280return value.toFixed(2);281}282</example>283</pattern>284285<pattern name="instanceof">286<description>Built-in instanceof type guard</description>287<example>288function handle(error: Error | string) {289 if (error instanceof Error) {290 return error.message;291 }292 return error;293}294</example>295</pattern>296297<pattern name="custom">298<description>Custom type guard function</description>299<example>300interface Cat { meow(): void; }301interface Dog { bark(): void; }302303function isCat(pet: Cat | Dog): pet is Cat {304return (pet as Cat).meow !== undefined;305}306</example>307</pattern>308309<pattern name="in_operator">310<description>Property existence type guard</description>311<example>312function move(animal: Fish | Bird) {313 if ("swim" in animal) {314 animal.swim();315 } else {316 animal.fly();317 }318}319</example>320</pattern>321</type_guards>322323<branded_types>324<pattern name="branded_primitives">325<description>Nominal typing via branding</description>326<example>327type UserId = string & { readonly **brand: unique symbol };328type OrderId = string & { readonly **brand: unique symbol };329330function createUserId(id: string): UserId {331return id as UserId;332}333</example>334<note>Prevent mixing similar primitive types</note>335</pattern>336</branded_types>337338<satisfies_operator>339<pattern name="type_checking_without_widening">340<description>Type checking without widening</description>341<example>342const config = {343endpoint: "/api",344timeout: 3000,345} satisfies Record<string, string | number>;346// config.endpoint is inferred as "/api" (literal), not string347</example>348</pattern>349</satisfies_operator>350</type_patterns>351352<runtime_patterns>353<error_handling>354<pattern name="result_type">355<description>Rust-inspired Result type for error handling</description>356<example>357type Result<T, E = Error> =358| { success: true; data: T }359| { success: false; error: E };360361function parseJson<T>(json: string): Result<T> {362try {363return { success: true, data: JSON.parse(json) };364} catch (e) {365return { success: false, error: e as Error };366}367}368</example>369</pattern>370371<pattern name="custom_errors">372<description>Custom error classes with additional context</description>373<example>374class ValidationError extends Error {375 constructor(376 message: string,377 public readonly field: string,378 public readonly code: string379 ) {380 super(message);381 this.name = "ValidationError";382 }383}384</example>385</pattern>386387<pattern name="error_cause">388<description>Error chaining with cause (ES2022+)</description>389<example>390try {391 await fetchData();392} catch (e) {393 throw new Error("Failed to fetch data", { cause: e });394}395</example>396</pattern>397</error_handling>398399<async_patterns>400<pattern name="promise_all">401<description>Parallel promise execution</description>402<example>403const [users, posts] = await Promise.all([404fetchUsers(),405fetchPosts(),406]);407</example>408</pattern>409410<pattern name="promise_allSettled">411<description>Handle mixed success/failure</description>412<example>413const results = await Promise.allSettled([414 fetchUser(1),415 fetchUser(2),416 fetchUser(3),417]);418419const successful = results420.filter((r): r is PromiseFulfilledResult<User> => r.status === "fulfilled")421.map((r) => r.value);422</example>423</pattern>424425<pattern name="async_iterator">426<description>Async generator for pagination</description>427<example>428async function* paginate<T>(fetchPage: (page: number) => Promise<T[]>) {429 let page = 0;430 while (true) {431 const items = await fetchPage(page++);432 if (items.length === 0) break;433 yield* items;434 }435}436437for await (const item of paginate(fetchUsers)) {438console.log(item);439}440</example>441</pattern>442</async_patterns>443444<module_patterns>445<pattern name="esm_exports">446<description>ES module export patterns</description>447<example>448// Named exports449export const helper = () => {};450export type Config = { /\* ... \_/ };451452// Default export453export default class Service {}454455// Re-exports456export { util } from "./util.js";457export type { UtilOptions } from "./util.js";458</example>459</pattern>460461<pattern name="barrel_exports">462<description>index.ts for clean imports</description>463<example>464// src/components/index.ts465export { Button } from "./Button.js";466export { Input } from "./Input.js";467export type { ButtonProps, InputProps } from "./types.js";468</example>469<warning>Can impact tree-shaking; use sparingly</warning>470</pattern>471472<pattern name="dynamic_import">473<description>Code splitting with dynamic imports</description>474<example>475const module = await import("./heavy-module.js");476module.doSomething();477</example>478</pattern>479</module_patterns>480</runtime_patterns>481482<tooling>483<eslint>484<pattern name="recommended_config">485<description>ESLint with TypeScript (flat config)</description>486<example>487// eslint.config.js488import eslint from "@eslint/js";489import tseslint from "typescript-eslint";490491export default tseslint.config(492eslint.configs.recommended,493...tseslint.configs.strictTypeChecked,494{495languageOptions: {496parserOptions: {497projectService: true,498tsconfigRootDir: import.meta.dirname,499},500},501}502);503</example>504<note>import.meta.dirname requires Node.js 20.11+ or 21.2+ (not available in Node.js 18 LTS)</note>505</pattern>506507<key_rules>508<rule name="@typescript-eslint/no-explicit-any">Prefer unknown over any</rule>509<rule name="@typescript-eslint/no-unused-vars">Detect unused variables</rule>510<rule name="@typescript-eslint/strict-boolean-expressions">Require explicit boolean conditions</rule>511<rule name="@typescript-eslint/no-floating-promises">Require awaiting promises</rule>512<rule name="@typescript-eslint/prefer-nullish-coalescing">Use ?? over ||</rule>513</key_rules>514</eslint>515516<prettier>517<pattern name="recommended_config">518<description>Prettier configuration for TypeScript</description>519<example>520{521 "semi": true,522 "singleQuote": false,523 "tabWidth": 2,524 "trailingComma": "es5",525 "printWidth": 100526}527</example>528</pattern>529</prettier>530531<testing>532<vitest>533<pattern name="config">534<description>Modern, fast test runner</description>535<example>536// vitest.config.ts537import { defineConfig } from "vitest/config";538539export default defineConfig({540test: {541globals: true,542environment: "node",543coverage: {544provider: "v8",545reporter: ["text", "json", "html"],546},547},548});549</example>550</pattern>551</vitest>552553<jest>554<pattern name="config">555<description>Jest configuration for TypeScript</description>556<example>557// jest.config.ts558import type { Config } from "jest";559560const config: Config = {561preset: "ts-jest",562testEnvironment: "node",563roots: ["<rootDir>/src"],564moduleNameMapper: {565"^@/(.\*)$": "<rootDir>/src/$1",566},567};568569export default config;570</example>571</pattern>572</jest>573</testing>574575<build_tools>576<tsc>577<tool name="tsc">578<description>TypeScript compiler commands</description>579<use_case name="compile">tsc - Compile TypeScript</use_case>580<use_case name="build">tsc --build - Incremental build (monorepo)</use_case>581<use_case name="check">tsc --noEmit - Type check only</use_case>582<use_case name="watch">tsc --watch - Watch mode</use_case>583</tool>584</tsc>585586<tsx>587<tool name="tsx">588<description>TypeScript execution with esbuild</description>589<use_case name="run">tsx src/index.ts - Run TypeScript directly</use_case>590<use_case name="watch">tsx watch src/index.ts - Watch mode</use_case>591</tool>592</tsx>593594<tsup>595<pattern name="config">596<description>Bundle TypeScript libraries</description>597<example>598// tsup.config.ts599import { defineConfig } from "tsup";600601export default defineConfig({602entry: ["src/index.ts"],603format: ["cjs", "esm"],604dts: true,605clean: true,606sourcemap: true,607});608</example>609</pattern>610</tsup>611</build_tools>612</tooling>613614<context7_integration>615<library_id>/microsoft/typescript</library_id>616<trust_score>9.9</trust_score>617<snippets>16397</snippets>618619<usage_pattern>620<step>Resolve library ID if needed (already known: /microsoft/typescript)</step>621<step>Fetch documentation with specific topic</step>622<examples>623<example topic="tsconfig">Configuration options and patterns</example>624<example topic="generics">Generic type patterns</example>625<example topic="utility types">Built-in utility types</example>626<example topic="module resolution">Module resolution strategies</example>627</examples>628</usage_pattern>629630<common_queries>631<query topic="strict mode">Strict compiler options</query>632<query topic="path mapping">Path aliases configuration</query>633<query topic="declaration files">Type declaration generation</query>634<query topic="nodenext">ESM support in Node.js</query>635</common_queries>636</context7_integration>637638<anti_patterns>639<avoid name="any_abuse">640<description>Overusing 'any' defeats type safety</description>641<instead>Use 'unknown' and narrow with type guards</instead>642</avoid>643644<avoid name="type_assertions">645<description>Excessive 'as' casts bypass type checking</description>646<instead>Use type guards or proper typing</instead>647</avoid>648649<avoid name="implicit_any">650<description>Missing type annotations with noImplicitAny disabled</description>651<instead>Enable strict mode, add explicit types</instead>652</avoid>653654<avoid name="barrel_overuse">655<description>Barrel files can hurt tree-shaking</description>656<instead>Use direct imports for large modules</instead>657</avoid>658659<avoid name="enums">660<description>Enums have runtime overhead and quirks</description>661<instead>Use const objects with 'as const'</instead>662<example>663const Status = {664 Active: "active",665 Inactive: "inactive",666} as const;667668type Status = (typeof Status)[keyof typeof Status];669</example>670</avoid>671672<avoid name="namespace">673<description>Namespaces are legacy, use ES modules</description>674<instead>Use regular imports/exports</instead>675</avoid>676677<avoid name="decorator_abuse">678<description>Decorators add complexity and are still experimental</description>679<instead>Prefer composition and higher-order functions</instead>680</avoid>681</anti_patterns>682683<best_practices>684<practice priority="critical">Enable strict mode in all projects</practice>685<practice priority="critical">Use noUncheckedIndexedAccess for safer array/object access</practice>686<practice priority="high">Prefer 'unknown' over 'any' for unknown types</practice>687<practice priority="high">Use 'satisfies' to check types without widening</practice>688<practice priority="high">Create branded types for domain primitives</practice>689<practice priority="medium">Use Result types for error handling over exceptions</practice>690<practice priority="medium">Keep type definitions close to usage</practice>691<practice priority="medium">Export types separately with 'export type'</practice>692<practice priority="medium">Use 'const' assertions for literal types</practice>693<practice priority="medium">Prefer interfaces for public APIs, types for unions/utilities</practice>694</best_practices>695696---697> Converted and distributed by [TomeVault](https://tomevault.io/claim/mtaku3) — claim your Tome and manage your conversions.698<!-- tomevault:4.0:skill_md:2026-04-13 -->