Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

effect-ts

БесплатноБез исполняемых скриптовНе проверен

Effect is a TypeScript library for typed errors, dependency injection, structured concurrency, retries, streams and schema validation. Use when someone asks…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

Effect-TS

Overview

Effect makes failures and dependencies part of a function's type. An Effect<A, E, R> produces A, may fail with E, and needs services R. The current line is Effect 4.x (npm latest is 4.0.6; 3.22.x is tagged prev). Version 4 merged many packages into effect (@effect/platform, @effect/rpc and others), all ecosystem packages share one version, and some APIs were renamed. Code from older tutorials (Context.Tag, Effect.catchAll, Schema.minLength) does not compile on 4.x. Migration guide: https://github.com/Effect-TS/effect/blob/main/MIGRATION.md

Requirements: strict: true in tsconfig.json, TypeScript 5.9 or newer.

npm install effect

Instructions

Typed errors with Effect.gen

Define errors with Data.TaggedError; the _tag is added for you and catchTag narrows on it. Inside a generator, yield* unwraps an effect and return yield* new MyError(...) fails with it.

// users.ts
import { Data, Effect } from "effect"

class UserNotFound extends Data.TaggedError("UserNotFound")<{ readonly userId: string }> {}
class DatabaseError extends Data.TaggedError("DatabaseError")<{ readonly cause: unknown }> {}

interface User { readonly id: string; readonly name: string; readonly email: string }
declare const db: { user: { findUnique(a: { where: { id: string } }): Promise<User | null> } }

export const getUser = (id: string) =>
  Effect.gen(function* () {
    const user = yield* Effect.tryPromise({
      try: () => db.user.findUnique({ where: { id } }),
      catch: (cause) => new DatabaseError({ cause }),
    })
    if (user === null) return yield* new UserNotFound({ userId: id })
    return user
  })
// Effect<User, DatabaseError | UserNotFound, never>

export const getUserOrGuest = (id: string) =>
  getUser(id).pipe(
    Effect.catchTag("UserNotFound", () =>
      Effect.succeed({ id: "guest", name: "Guest", email: "[email protected]" })),
  ) // DatabaseError stays in the error type

Renamed in 4.x: Effect.catchAll is now Effect.catch, catchAllCause is catchCause, catchSome is catchFilter. catchTag and catchTags are unchanged.

Services and layers

In 4.x all of Context.Tag, Context.GenericTag, Effect.Tag and Effect.Service are replaced by Context.Service. The type parameters come first and the identifier goes in the second call. Static accessor proxies are gone: yield* the service (preferred) or use Service.use((s) => ...).

// services.ts
import { Context, Data, Effect, Layer } from "effect"

class DatabaseError extends Data.TaggedError("DatabaseError")<{ readonly cause: unknown }> {}
class UserNotFound extends Data.TaggedError("UserNotFound")<{ readonly userId: string }> {}
interface User { readonly id: string; readonly name: string; readonly email: string }
declare const prisma: { user: { findUnique(a: { where: { id: string } }): Promise<User | null> } }

export class UserRepo extends Context.Service<UserRepo, {
  findById(id: string): Effect.Effect<User | null, DatabaseError>
}>()("app/UserRepo") {
  static readonly layer = Layer.succeed(UserRepo, {
    findById: (id: string) =>
      Effect.tryPromise({
        try: () => prisma.user.findUnique({ where: { id } }),
        catch: (cause) => new DatabaseError({ cause }),
      }),
  })
}

// Effect.fn names the function for traces and keeps generator ergonomics
export const getUser = Effect.fn("getUser")(function* (id: string) {
  const repo = yield* UserRepo
  const user = yield* repo.findById(id)
  if (user === null) return yield* new UserNotFound({ userId: id })
  return user
}) // (id: string) => Effect<User, DatabaseError | UserNotFound, UserRepo>

// Entry point: provide the real layer and run once
Effect.runPromise(getUser("u_1042").pipe(Effect.provide(UserRepo.layer)))

// Test: same logic, fake layer
const FakeRepo = Layer.succeed(UserRepo, {
  findById: (id: string) => Effect.succeed({ id, name: "Test User", email: "[email protected]" }),
})
Effect.runPromise(getUser("u_1").pipe(Effect.provide(FakeRepo)))

Use Layer.effect(Service, effectBuildingTheImplementation) when building the service needs other services or resources.

Concurrency, retry, timeout

// resilience.ts
import { Duration, Effect, Schedule } from "effect"

// At most 5 at once; results keep input order
export const processAll = (ids: string[]) =>
  Effect.forEach(ids, (id) => processOne(id), { concurrency: 5 })

export const fetchJson = (url: string) =>
  Effect.tryPromise(() => fetch(url).then((r) => r.json() as Promise<unknown>)).pipe(
    Effect.retry({
      schedule: Schedule.exponential(Duration.seconds(1)).pipe(Schedule.jittered),
      times: 3,
    }),
    Effect.timeout(Duration.seconds(5)),
  )

// First success wins, the loser is interrupted
export const fastest = Effect.race(fetchJson("https://api-a.northwind.dev/rates"), fetchJson("https://api-b.northwind.dev/rates"))
declare const processOne: (id: string)
Полный SKILL.md на GitHub

Установить effect-ts в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл effect-ts?

Effect is a TypeScript library for typed errors, dependency injection, structured concurrency, retries, streams and schema validation. Use when someone asks to "handle errors without try-catch", "type-safe error handling in TypeScript", "dependency injection without classes", "retry with backoff", "concurrent TypeScript", "Effect library" or "replace Promise chains with typed effects". Targets Effect 4.x and notes the changes from 3.x.

Как установить скилл effect-ts?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл effect-ts запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить effect-ts с