Categories
Tags
Ai 生成 API学习 API简化 api请求 API调用 best-practices Blogging Caching catchTag catchTags class CLI Config context Context Context.Tag CSS Customization Demo development DocC Docker dual API Effect effect Effect.Service Effect.succeed Example extension ffmpeg filterOrFail flatMap Fuwari gen generator grep hooks HTML HTTP响应 IDE自动补全 iOS javascript JavaScript Javascript Layer.effect Layer.provide Layers Linux Markdown Mock n8n Next.js ParseError pipe pokemon PostCSS process.env progress Promise promise provideService PWA react React React Hook Form React Query React Router react-native Scheduler Schema Schema.Class security Service Worker Services SSR state-management suspense Tagged Errors TaggedError TanStack Query TanStack Start tips tryPromise tsconfig TypeScript typescript Video VS Code vscode Web API Web Development yield yt-dlp Zod 不透明类型 二叉树 代码组织 任务调度 优先级 使用服务 依赖注入 依赖管理 值语义 入门教程 最佳实践 最小堆 函数式编程 函数组合 前端 前端开发 副作用 副作用控制 可视化 可组合性 可维护性 可访问性 命令行 响应过滤 多个错误 实现 实践指南 层 层依赖 层组合 工具链 并发控制 应用架构 延迟执行 开发技巧 开发教程 开源 异步处理 异步操作 异步编程 性能优化 手写系列 排序 接口设计 插件开发 数据结构 数据获取 数据解码 数据验证 无限滚动 日历 日志分析 服务 服务依赖 服务定义 服务实现 服务提供 测试 源码分析 状态管理 环境变量 生成器 离线支持 程序分离 算法 类型安全 类型定义 类型推断 类型系统 类定义 线性代码 组合 翻译 自动化 自定义错误 表单验证 记忆化 设计模式 语义化 运维 运行时验证 部分应用 配置 配置变量 配置服务 配置管理 重构 错误处理 错误定义 错误恢复 项目设置
437 words
2 minutes
[Effect Layers] 03. 从实现推断服务类型
https://github.com/typeonce-dev/effect-getting-started-course
你现在可能会注意到 getPokemon 的类型错误:
Type 'BuildPokeApiUrl | PokemonCollection' is not assignable to type 'never'.这是因为我们手动定义了 PokeApiImpl 接口,它不再符合新的实现(不期望依赖关系):
WARNING依赖类型错误
每当你看到形如
Type 'Service' is not assignable to type 'never'的类型问题时,它可能与缺失/过时的依赖关系有关(在这个例子中是BuildPokeApiUrl和PokemonCollection)
PokeApi.ts
interface PokeApiImpl {
/// `getPokemon` 的依赖关系是 `never`
/// (`never` 是未定义时的默认类型)
///
/// 但我们的实现使用了 `BuildPokeApiUrl` 和 `PokemonCollection`
/// ⛔️ 不能赋值给 `never`!
readonly getPokemon: Effect.Effect<
Pokemon,
FetchError | JsonError | ParseResult.ParseError | ConfigError
>;
}
export class PokeApi extends Context.Tag("PokeApi")<PokeApi, PokeApiImpl>() {保持实现和类型同步是一件痛苦的事情,我们不想这样做。从实际实现中推导类型更快。
好消息!我们可以使用TypeScript的 typeof 来做到这一点。
我们首先定义一个包含服务实现的 make 值,并在创建 Context 服务时提供其类型定义:
PokeApi.ts
const make = {
getPokemon: Effect.gen(function* () {
const pokemonCollection = yield* PokemonCollection;
const buildPokeApiUrl = yield* BuildPokeApiUrl;
const requestUrl = buildPokeApiUrl({ name: pokemonCollection[0] });
const response = yield* Effect.tryPromise({
try: () => fetch(requestUrl),
catch: () => new FetchError(),
});
if (!response.ok) {
return yield* new FetchError();
}
const json = yield* Effect.tryPromise({
try: () => response.json(),
catch: () => new JsonError(),
});
return yield* Schema.decodeUnknown(Pokemon)(json);
}),
};
export class PokeApi extends Context.Tag("PokeApi")<PokeApi, typeof make>() {
static readonly Live = PokeApi.of(make);
}现在服务类型是实现驱动的:我们可以专注于实现(当语言支持类型推断时,永远不必手动输入类型)。
TIP推荐模式
这种
make+typeof模式在Effect中是常见且推荐的。
NOTE由于我们更改了服务类型,我们还需要更新
Test实现。
我们将在即将到来的课程中修复测试 🔜