379 words
2 minutes
[Effect Schema] 01. 数据验证的问题

数据验证的问题#

在处理 API 响应时,我们经常面临一个关键问题:如何确保接收到的数据符合我们期望的类型结构?让我们通过一个实际例子来探讨这个问题。

考虑以下异步函数,它从 PokéAPI 获取数据:

const main = async (): Promise<unknown> => { const response = await fetch("https://pokeapi.co/api/v2/pokemon/garchomp/"); if (!response.ok) { throw new Error("Response not okay"); } const json = await response.json(); return json; };

我们如何确保获得的是一个 Pokémon 数据?

首先,让我们为 Pokémon 定义一个简单的 interface(基于 PokéApi 的响应):

interface Pokemon { id: number; order: number; name: string; height: number; weight: number; }

现在,我们需要将 API 响应从 unknown 类型转换为 Pokemon 类型。

这在纯 TypeScript 中是复杂的。以至于大多数人经常默认使用 as 进行类型转换:

interface Pokemon { id: number; order: number; name: string; height: number; weight: number; } const main = async (): Promise<Pokemon> => { const response = await fetch("https://pokeapi.co/api/v2/pokemon/garchomp/"); if (!response.ok) { throw new Error("Response not okay"); } const json = await response.json(); return json as Pokemon; };

TypeScript 中的 as 是一种绕过类型验证的方式。你在说:“我比你更了解 TypeScript,所以听我的,把这个类型设为 Pokemon

as 会让你的代码库暴露于运行时错误,请极其谨慎地使用它(理想情况下永远不要使用!

实际上,我们无法确定响应确实是一个有效的 Pokemon。我们需要引入运行时验证来检查这一点。

这就是 Effect Schema 来拯救我们的地方!

[Effect Schema] 01. 数据验证的问题
https://0bipinnata0.my/posts/course/effect-beginners-complete-getting-started/effect-schema/01-the-problem-with-data-validation/
Author
0bipinnata0
Published at
2025-08-30 16:58:05