/typescript:codingfrom typescript
Use when writing or reviewing TypeScript, covering functional design with Effect, Schema, and algebraic data types
Ships in typescript. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Covers functional TypeScript on Effect modules.
[REFERENCES]:
One declaration states each concept, its set of cases included, and every other form derives from it:
class Digits extends Schema.Class<Digits, { readonly brand: unique symbol }>('Digits')({
system: Schema.String,
table: Schema.Array(Schema.String.check(Schema.isPattern(/^\p{Nd}$/u))).check(Schema.isBetweenLength(10, 10)),
}) {
static readonly #bySystem = pipe(
Intl.supportedValuesOf('numberingSystem'),
Record.fromIterableWith((system) => [system, Array.makeBy(10, new Intl.NumberFormat(undefined, { numberingSystem: system }).format)]),
Record.filterMap((table, system) => Schema.decodeResult(Digits)({ system, table })),
);
static readonly of = (system: string): Option.Option<Digits> => Record.get(Digits.#bySystem, system);
}
Intl.supportedValuesOf lists every numbering system the runtime holds, the class check keeps the decimal ones, and Digits.of reads one by key, so a runtime adding a system adds a row with no edit:
Struct.pick(value, Struct.keys(Reference.fields)), Control.mapFields), a key list restating them{ begin, end }), a tuple zipped against role values misaligning when either order changesas const record{ awk: { idioms, effects } }) read by keyof typeof table, parallel tables per column restating themRecord.map over each axis's record where a nested domain value reads them, else one Array.cartesianWithArray.cartesianWith builds them, returning Option.none() past the limitundefined, a literal test choosing that default restating itconstFunction.memoize or a fieldSignatures state every value a function accepts and every outcome its caller handles. Parameters and fields are readonly, arrays readonly A[], or Array.NonEmptyReadonlyArray<A> where the rule needs an element, and Effect.forEach over a non-empty input (Array.range, Array.makeBy) returns one.
Total functions return a declared output for each accepted input, narrowing the input to a decoded type or widening the output to Option, Result, or Effect:
Digits, Control['kind'])Schema.decodeUnknownOption(Schema.NumberFromString) states every outcome of a parsePure functions depend on their arguments alone and cause no side effect. Clock, randomness, environment, logging, and I/O are effects.
Bindings are const, and values build in one expression stating each field at creation:
const kashidaPlaces = (text: string, rows: Parameters<typeof candidates>[2]) =>
words(text)
.map((word) => joins(text, word).flatMap((join) => candidates(text, join, rows)))
.filter(Array.isArrayNonEmpty)
.map(Array.min(BY_RANK))
.toSorted(BY_RANK);
words, joins, and candidates read the joining positions of Arabic text, and BY_RANK orders a place by its rank. Array.isArrayNonEmpty narrows each word's places, so Array.min returns the best one with no absent case:
filter, every, join, reduce, or Set relations (union, difference, isSupersetOf), Effect modules othersmap, toArray, join) traverse a Map, Set, or matchAll result, a spread or Array.fromIterable restating thembench run on the pinned Node measures iterator helpers or Set methods fasterRecord.collect maps entries to an array and Record.keys lists keys, after any Record.filter, Object.entries pairs restating themRecord.filterMap maps through a Result: Result.failVoid drops an entry, Result.fromOption enters a lookup, Schema.decodeResult validatesRecord.getSomes, which widens keys; closed optional fields spread Option.map field objects through Option.getOrUndefinedOption over the non-empty set of cases needing them, each case joining through Option.toArrayStruct.renameKeys maps keys to the spelling a host reads, Struct.evolveKeys computes them, a destructure rebuilding the object restating bothNumber.sumAll, BigDecimal.sumAll, Array.max, Array.groupBy) state their fold, Math.sumPrecise a Node float sumArray.zip in pairs and Iterator.zip in larger sets, browser and Adobe host code keeping Array.ziplib esnext declares members the pinned V8 lacks (Iterator.chunks, Promise.allKeyed), and code calls a member once node runs itreduce with a seed folds a reduction no member names, Array.mapAccum(xs, seed, (state, x) => [next, y]) maps under a running stateArray.makeBy and Array.range generate sequences from a length or boundsArray.window(values, 2) returns, a gap filling from Array.range over its pairRegExp.escape(text) builds a pattern from literal text, a replaceAll escape restating itUnions own their fold: Schema.TaggedUnion through match, Data.taggedEnum through $match and Option.filter(<option>, <enum>.$is(<tag>)) for a field of one case, and any other value through Match:
const verdict = Match.value({ command: Option.getOrUndefined(command), inPlace, json: jsonParse.test(written) }).pipe(
Match.when({ command: Match.defined }, ({ command: words }) => rewrite(invocation, words)),
Match.when({ inPlace: true }, () => [{ deny: `${name} -i edits files in place.`, advice: 'Edit them with sd.' }]),
Match.when({ json: true }, () => [{ deny: `${name} inline code parses JSON.`, advice: 'Read it with jq.' }]),
Match.orElse(() => []),
);
command is an Option of the words an idiom restates the invocation as, rewrite builds that edit, and inPlace and json are facts of the invocation and its code (jsonParse matching a JSON parse). Arms read facts by name, and Option.getOrUndefined lets Match.defined narrow the command:
Match.exhaustive closes a decision over a closed union, Match.orElse closes an open one with a fallback outcomeMatch.option closes a match where unmatched input is absence and Match.result one for filterMap, Match.orElse to none restating themMatch.when takes a refinement or a partial pattern with a value or refinement per field (Schema.is(X.fields.f)), Match.whenOr alternativesMatch.not takes an exclusion, Match.orElse closing the arms it leavesMatch.valueTags(value, handlers) folds a _tag union with one handler per tag{ role, below: Predicate.isTupleOf(2) }), a path no arm names falling to the refusal armArray.ensureEqual.equals(stdin, Stdin.Piped({ pipeline, index }))), a tag test and a === per field restating itMatch.discriminatorsExhaustive(key)(handlers), a 'k' in x or type !== branch restating itPredicate (isObject, hasProperty, isTagged) composed through Predicate.and, or, and notError.isError refines errors, as Predicate.isError tests instanceof Error and misses an error from another realmPredicate.isTagged inside a filter narrows nothing after it, and filterMap(Filter.tagged(tag)) narrows to the caseTypeScript runs tail calls on the stack, and a recursion's depth bound selects its form:
| [INDEX] | [APPROACH] | [USE_WHEN] |
|---|---|---|
| [01] | Direct recursion | Depth small and bounded (parsed tree), or consumed input bounding it |
| [02] | Array.unfold | Each state yields one element and an Option of next state (a folder's ancestors) |
| [03] | Array.mapAccum | Evaluation threading state through a sequence (an assignment reaching next word) |
| [04] | Effect.suspend loop | Effectful transition at unbounded depth |
| [05] | Stream.paginate | Each round yields outputs and an Option of next state (cursor, frontier, fixed point) |
| [06] | Graph traversal | Shared or cyclic successors |
oxfmt prints a call with more than one argument one argument per line at any width when more than one argument is an inline function or one argument is a call taking an inline function:
void keep a block body around their statement, typescript/strict-void-return refusing a value-returning expression bodyData-first calls nested through their first argument become one pipe from the innermost subject, each call a data-last step at one level:
const displayed = (query: Option.Option<string>, candidates: readonly string[], limit: number) =>
pipe(
query,
Option.map((wanted) => Unmatched.rank(wanted, candidates)),
Option.filter(Array.isReadonlyArrayNonEmpty),
Option.getOrElse(() => candidates),
Array.take(limit),
);
Unmatched.rank orders candidates by their match to the query, and displayed prints one level where Array.take around Option.getOrElse around Option.filter around Option.map printed a level per call.
Forbidden forms take the rebuild in their row, each module imported from effect:
| [INDEX] | [FORBIDDEN] | [REBUILD] |
|---|---|---|
| [01] | acquireUseRelease, acquireRelease over a disposable handle | acquireDisposable piped through each use, Effect.scoped last |
| [02] | Callback reading an Effect.all tuple | yield* Effect.all([...]) in a generator, fold as its return |
| [03] | flatMap into Option.match, .value after an early return | Option.match(yield* effect, {...}) in a generator |
| [04] | Array pattern holding an object pattern | Array.headNonEmpty(items).<field> destructured flat |
| [05] | Option.liftPredicate, then Option.flatMap to a field | Option.filter(Option.fromUndefinedOr(field), predicate) |
| [06] | Result.fromOption(Option.map(option, f), g) | Option.match arms returning Result.fail, Result.succeed |
| [07] | Lookup pairs built, then walked by forEach | One walk, each lookup through Option.flatMapNullishOr |
| [08] | Effect.forEach yielding Option, then Array.getSomes | Effect.filterMapEffect with a filter yielding a Result |
| [09] | pipe(<call>, Function.constVoid) standing for a statement | Block-bodied callback |
| [10] | Effect.succeed(value) mapped or joined in Effect.all | Plain value read inside Effect.map over the effect |
| [11] | match arms repeating one result across tags | matchOrElse with the differing tags as arms |
| [12] | Array.match into Option, then Array.getSomes | filter(Array.isArrayNonEmpty), then the non-empty member |
| [13] | Set grown until next.size === held.size | Graph.dfs over Graph.fromSnapshot |
| [14] | relative(a, b).startsWith('..'), startsWith(folder + '/') | path.resolveWithin(folder, relative) returning Some |
| [15] | Stream.runFold(init, (_, last) => last) | Stream.runLast |
Effect.filterMapEffect returns successes in completion order under concurrency, and an Option held before the effect keeps Effect.transposeOption. Effect.when takes its condition as an Effect<boolean>, so a flag computed before the call enters as Effect.succeed(flag).
Records a signature names are a class over their schema, Schema.Opaque over a struct, array, or tuple for plain data and Schema.Class for instances with getters and methods. Data inside the process is Data.Class and Data.taggedEnum where it holds a name or operations, and a module-private record stays a readonly object Equal compares by its keys.
Every function returns an explicit outcome type, and one type serves one concern:
| [INDEX] | [TYPE] | [CONCERN] |
|---|---|---|
| [01] | Option<A> | Absence without error |
| [02] | Result<A, E> | Synchronous failure in pure computation |
| [03] | Effect<A, E, R> | Effect with typed failure and services it reads |
| [04] | Stream<A, E, R> | Values over time with one failure channel |
| [05] | Exit<A, E> | Completed outcome a host reads |
| [06] | Cause<E> | Every failure, defect, and interruption of one fiber |
Input boundaries select the outcome type, functions preserve it, and one conversion point uses the function named for its target (Effect.fromOption, Effect.fromResult, Option.fromNullishOr, Result.fromOption). null and undefined appear at a host API alone, a host field whose absence means a default reads field ?? default at the read, an optional value passes directly to a host prop accepting undefined and through a conditional spread to one refusing it, and Option stands where a consumer acts on absence. Absent text stays undefined or Option, never '', and text with an optional part is one expression choosing between complete values (Option.match(tag, { onNone: () => name, onSome: (suffix) => `${name}-${suffix}` })); '' stands only where a host input spells unset as '' (a JSX value, a <select> placeholder), decoded back to absence at that input. Cases sharing an absent spelling are a tagged enum compared through Equal, as a session and an agent both keyed '' collide. Casts and ! never stand in for a presence proof, a decode or Effect.fromNullishOr supplying it. Empty arrays are values, Option<readonly A[]> stands where a consumer treats no collection and an empty one differently.
Each package declares one error class for the expected failures its producers report, holding a reason case for each response a caller gives with the data that response reads, the subject that failed, and a foreign cause where one exists. One static derives message from subject, reason tag, and reason fields, and no call site, match arm, or table spells a sentence:
class HostError extends Schema.TaggedError<HostError, { readonly brand: unique symbol }>()('HostError', {
reason: Schema.TaggedUnion({ Refused: {}, Unavailable: {}, Unsupported: { member: Schema.String } }),
subject: Schema.String,
cause: Schema.optionalKey(Schema.Defect()),
message: Schema.String,
}) {
static readonly of = (reason: HostError['reason'], subject: string) => (cause?: unknown) =>
HostError.make({ reason, subject, ...(cause === undefined ? {} : { cause }), message: [subject, String.toLowerCase(reason._tag), ...Record.values(Struct.omit(reason, ['_tag']))].join(' ') });
static readonly refused = (subject: string) => HostError.of({ _tag: 'Refused' }, subject);
override readonly [ErrorReporter.severity]: LogLevel.Severity = this.reason._tag === 'Unavailable' ? 'Warn' : 'Info';
}
HostError.refused('panels and menu areas') is the catch of each host call reading them. of omits an absent cause, a cause: undefined key decoding as null across a JSON wire, and keeps a present one out of message, as Cause.pretty, a logger, and Formatter.format of the error each print its chain once:
message is a field the constructing static computes, an own property structuredClone and a worker's serializer copy where a getter is lost[ErrorReporter.severity] gives a reporter the level of each reason, 'Info' where the class sets nonereturn yield* raises one in a generator and a handler returning one fails with itEffect.when(error, condition) takes an instance as its effect, an Effect.fail or flow(make, Effect.fail) around one restating itSchemaError, HttpClientError, Cause.TimeoutError) stay in E unchangedEffect.orDieCause error naming them (NoSuchElementError, IllegalArgumentError)_tag, a constructor's name, Struct.keys(X.fields), X.literals, a tool's name), a literal copy driftingmessage alone (Nx without --verbose, an MCP isError result) take the cause from one boundary printing Formatter.format(error) or Cause.prettynew Cause.UnknownError(value, message), the message naming the refusalSchema.encodeResult(Schema.fromJsonString(Schema.toCodecJson(S))), never StringSchema.NonEmptyArray(Finding), its raise static failing on a non-empty listcause under a subject a caller acts on, a String(cause) or error.message detail flattening its chainDependent steps bind and independent ones combine through Effect.all:
Effect.gen holds a sequence where a later step reads more than one earlier value, pipe holds a linear chain, one step is the effect itselfOption inside an effect included, and a consumer matches it once at the endconst run = Effect.fn('run')(function* (argv: Array.NonEmptyReadonlyArray<string>, { within = Duration.infinity, ...options }: ChildProcess.CommandOptions & { readonly within?: Duration.Input | undefined } = {}) {
const command = CommandLine.display(argv);
const handle = yield* spawn(argv, { stdin: 'ignore', forceKillAfter: '100 millis', ...options, detached: false });
const [stdout, stderr, code] = yield* Effect.all([handle.stdout.pipe(Stream.decodeText, Stream.mkString), handle.stderr.pipe(Stream.decodeText, Stream.mkString), handle.exitCode], { concurrency: 'unbounded' }).pipe(
Effect.timeoutOrElse({ duration: within, orElse: () => new Cause.TimeoutError(`${command} ran past ${Duration.format(Duration.fromInputUnsafe(within))}`) }),
);
const exited = { command, code, stdout, stderr };
return code === 0 ? exited : yield* ExitError.of(exited);
}, Effect.scoped);
spawn starts a ChildProcess with trace context in its environment, both pipes drain beside the exit code under the within deadline, and the code selects between the output and an ExitError the generator raises. Dependency structure and concurrency bound select a traversal over many effects:
| [INDEX] | [SCENARIO] | [TRAVERSAL] | [BEHAVIOR] |
|---|---|---|---|
| [01] | Independent checks | Effect.validate | Runs every check, keeps every failure |
| [02] | Independent effects | Effect.forEach with concurrency: 'unbounded' | Overlaps, interrupts rest on failure |
| [03] | Dependent or ordered effects | Effect.forEach without concurrency | Serial, stops at first failure |
| [04] | Bounded concurrency | Effect.forEach with concurrency: <n> | At most <n> effects at once |
| [05] | Every effect, failures kept | Effect.partition | Runs all, returns successes and failures |
| [06] | Every outcome kept in order | Effect.all with mode: 'result' | Runs all, one Result per effect |
| [07] | Every effect, causes joined | Exit.asVoidAll over Effect.forEach(items, Effect.exit) | Runs all, fails with every cause in E |
| [08] | Outcomes up to first failure | Stream.takeUntil(Result.isFailure) over Effect.result | Serial, keeps outcomes to the failure |
| [09] | First success, misses kept | Effect.flip(Effect.forEach(items, flow(f, Effect.flip))) | Serial, fails with every miss in order |
| [10] | Effectful predicate | Effect.filter(items, (item) => Effect<boolean>) | Keeps items yielding true |
| [11] | First effectful match | Effect.findFirst(items, (item) => Effect<boolean>) | Serial, runs no item after first match |
| [12] | First match mapped | Effect.findFirstFilter(items, (item) => Effect<Result>) | Serial, returns the first success value |
Effect.firstSuccessOf fails with its last error alone, so alternatives whose misses each list candidates take row 09 and merge the misses into one error.
Each valid state a consumer inspects is one case. Counting the values a type allows (a product multiplies its fields' counts, an optional field adds one) exposes states no case needs:
region beside windows and element), an optional union describing it in proseconst Condition = Schema.TaggedUnion({
Value: { at: Locator, value: Value },
Documents: { held: Schema.Boolean },
Modal: { at: Schema.NullOr(Locator) },
});
const read = Condition.match({
Value: ({ at }) => Option.some(at),
Documents: () => Option.none(),
Modal: ({ at }) => Option.fromNullOr(at),
});
Condition is one fact a control's presence depends on, Locator the encoded path of a control or dialog, Value a read value, and read the control or dialog a condition names.
Effect<A, E, R> describes a program that succeeds with A, fails with E, reads services R, and performs nothing until a runtime runs it. Promises are eager, enter through Effect.tryPromise, and leave through a host runtime call:
Effect.sync defers an infallible side effect, Effect.try a throwing one, its catch wrapping the throw in the package error or a SchemaIssueEffect.promise turns a rejection into a defect, so a host promise enters through Effect.tryPromise with the package errorEffect.tryPromise each with their own reason, a .then chain inside one giving every step one failureEffect.callback adapts a callback API, with registration receiving an AbortSignal and returning a cleanup effectDeferred the registering function awaits restate Effect.callback, except where a host callback must throw to roll backEffect.tryPromise passes a try declaring (signal) an AbortSignal interruption aborts, a rest or defaulted parameter receiving undefinedEffect.abortSignal yields a signal its scope aborts on close, for a host's abortSignal or { signal } optionconst page = (assets: Fetcher) =>
Effect.tryPromise({ try: (signal) => assets.fetch(new Request('http://localhost/', { signal })), catch: HostingError.of('Template', 'fetch') }).pipe(
Effect.filterOrFail(({ ok }) => ok, ({ status }) => HostingError.of('Template', `answer ${status}`)()),
Effect.flatMap((response) => Effect.tryPromise({ try: () => response.text(), catch: HostingError.of('Template', 'read') })),
);
Fetcher is the Workers binding type of static assets and HostingError.of(subject, step) the package error's constructor, interruption aborts its fetch, and the fetch, the status, and the body read each fail with their own reason.
Consumers receive the narrowest dependency they read: a value for a stable snapshot, an effect for an operation run on demand, and a service for a capability a program reads through its environment. Contracts mark members some implementers lack optional, read as engine.exclusive?.(client, plan) ?? plan, and functions take Pick<Contract, '<key>'>. A stub returning Effect.void or Option.none(), or an Option<Option<A>> whose outer level means the implementer lacks the member, restates absence.
Failure policies are distinct operations:
Effect.catchtimeout fails with TimeoutError, timeoutOrElse with a reason naming what never arrived, timeoutOption with noneEffect.onError(step, () => Effect.orDie(inverse)), keeping the step's failure in EEffect.acquireRelease(step, (_, exit) => Exit.isFailure(exit) ? inverse : Effect.void)left.size < failed.size && left.isSubsetOf(failed)), a fixed count retrying a stuck stepE, and a fallback, default, or retry hiding one is a defectLibraries return their outcome type with their own error, and the application composes retry schedule, fallback order, and cache around it.
Quantities with a unit are values of their module, a plain number holds a count or a dimensionless ratio:
SemVer holds versions, decoded through Schema.SemVerFromString and written through SemVer.format, a \d+\.\d+\.\d+ pattern restating themDuration holds elapsed times, a millisecond number at an API taking one, and text typed `${number} ${Duration.Unit}` is an undecoded inputDateTime holds instants and zoned times, Date appears at an API taking oneBigDecimal holds money and exact decimal arithmetic and ByteSize sizesDuration.format and ByteSize.format in fixed English, DateTime.formatIso, CommandLine.displayfileURLToPath, foreign values through Formatter.format, and a template spelling a unit, plural, range, or list restates an Intl memberSecureRandom.SecureRandom service's uuidV7 creates identifiers, module uuidV7Unsafe where code reads no service (an event handler)Intl instances built once outside their reader segment words and format numbers, lists, plurals, and times in a caller locale, else the host'sIntl format and compare are bound getters a step takes by reference (Array.makeBy(n, formatter.format))style: 'unit' NumberFormat per byte unit over ByteSize.toUnit, at the largest unit the rounded value reachesDateTime.formatIntl, offsets through RelativeTimeFormat at the largest Duration.to<Unit> reaching 1DurationFormat over Duration.parts, its sub-millisecond nanos split into microseconds and nanosecondsIntl.LDMLPluralRule record of functions over the formatted count, other required, a PluralRules per rule typeformat(0), a fixed minimumIntegerDigits restating the widthEquivalence over Intl.Collator(locale, { usage: 'search', sensitivity: 'base', ignorePunctuation: true })sensitivity: 'base' with ignorePunctuation equates &File with File and Save As… with Save As, which 'accent' keeps apartDigits.fold(text.normalize('NFKD').replaceAll(/\p{M}/gu, ''))) before rankingu match digits through \p{Nd}, \d reading ASCII aloneClasses hold their data with operations reading one instance as methods and getters, statics building or relating instances. Concepts caller data configures are a Schema.Class of the data with each use a method:
never, filled where no derivation reachesObject.assign or an expando setsfindPackageJSON, crypto.hash, node:net BoundSocket) replace a package, a shell-out, or a parse of tool outputnode: module go through one service over a node:ffi symbol image, in place of a spawned toolcalculateConfigForFile, rustc --print, jscpd --debug)GlobalWorkerOptions.workerSrc) stay unset, each instance taking the value through its constructor option< escape in React <style> text restating itwith { type: 'json' }, a read and decode standing for files changing after build() => import('<path>') thunks typed by the import, a schema over the loaded module restating itimport()export { X }, a thing, ThingView, or thingFor restating themtypescript:effect for Effect module families and telemetrytypescript:testing for suitesreferences/analysis.md (opens in a new tab)references/concurrency.md (opens in a new tab)references/data.md (opens in a new tab)references/functions.md (opens in a new tab)references/results.md (opens in a new tab)references/schema.md (opens in a new tab)references/services.md (opens in a new tab)references/types.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub bsamiee/rasm --plugin typescript4 skills in this plugin
/debuggingUse when JavaScript or TypeScript misbehaves at runtime in Node, a browser page, a worker, a test runner, or a single executable and its cause is unproven, covering js-debug launch and attach routes, child programs, source maps, exception filters, Node's probe mode, and the evidence Node writes/effectUse when calling an Effect module family, covering HttpApi, HTTP clients and routes, RPC, sockets and atoms, SQL, AI, MCP and chat platforms, child processes, workers and CLIs, persistence and durable execution, files, encodings, crypto, and telemetry/testingUse when writing, running, or debugging TypeScript tests, covering Vitest and @effect/vitest, isolation options, type tests, benchmarks, controlled time, in-memory contract clients, service doubles, generated inputs, fixtures, browser and Workers suites, containers, and Playwright