类型
我梦想着在ECMAScript西部的野外进行适当的元编程. 平行
eMAScript拥有类型、宏和适当的模块系统的宇宙。 何处
模块不管环境和运行时间。 和我们之间
系统是标准化的,来自服务器运行时间的代码在浏览器中工作. 不过
唉,我们被困在一个糟糕的笑话 宇宙中TypeScript是下一个
最好的东西。 所以,我介绍给你,TypeFatch, 一个零成本生成工具
类型安全 fetch openAPI的客户端计划. 随处可见
fetch,可以在任何地方使用 TypeScript .
使用量
要使用TypeFetch,需要有一个OpenAPI schema. 您可以提供 本地文件路径或 URL 到 schema( 可以是 json 或 yaml) , 那么 您只需要使用 deno、 节点或任何其他 JavaScript 运行 cli 运行时间 日语 登记.
deno run -A jsr:@denosaurs/typefetch
Usage: typefetch [OPTIONS] <PATH>
Options:
-h, --help Print this help message
-V, --version Print the version of TypeFetch
-o, --output <PATH> Output file path (default: typefetch.d.ts)
--config <PATH> File path to the tsconfig.json file
--import <PATH> Import path for TypeFetch (default: https://raw.githubusercontent.com/denosaurs/typefetch/main)
--base-urls <URLS> A comma separated list of custom base urls for paths to start with
--include-server-urls Include server URLs from the schema in the generated paths (default: true)
--include-absolute-url Include absolute URLs in the generated paths (default: false)
--include-relative-url Include relative URLs in the generated paths (default: false)
--experimental-urlsearchparams Enable the experimental fully typed URLSearchParams type (default: false)
示例
deno run -A jsr:@denosaurs/typefetch https://api.jsr.io/.well-known/openapi
这将生成一个 typefetch.d.ts 在当前目录中的文件,它将
修改全球范围和 fetch 函数和
计划中定义的所有类型。 例如:
declare global {
...
/**
* Returns a list of packages
* @summary List packages
*/
function fetch(
input: `https://api.jsr.io/packages` | `/packages`,
init?: Omit<RequestInit, "method" | "body" | "headers"> & {
method: "GET";
},
): Promise<
& Omit<
Response,
"ok" | "status" | "arrayBuffer" | "blob" | "formData" | "json" | "text"
>
& (
| ({
ok: true;
status: 200;
json(): Promise<{ items: Package[]; total: number }>;
text(): Promise<JSONString<{ items: Package[]; total: number }>>;
})
| ({
ok: false;
status: 400;
json(): Promise<Error>;
text(): Promise<JSONString<Error>>;
})
)
>;
...
}
现在允许您使用 fetch 函数与
https://api.jsr.io/packages 终点如下:
const response = await fetch("https://api.jsr.io/packages");
// The ok and status properties work as discriminators here to narrow the
// types of the response. That way the json and text methods are made
// type-safe.
if (response.ok) {
console.assert(response.status === 200);
const { items, total } = await response.json();
// even this works because we augment the global JSON object!
const { items, total } = JSON.parse(await response.text());
} else {
console.assert(response.status === 400);
const error = await response.json();
// or
const error = JSON.parse(await response.text());
}
维护者
- 伊莱亚斯·斯约格林(英语:Elias Sjögreen (U@eliassjogreen (英语)(中文(简体) )
捐款
拉出请求、问题和反馈是非常受欢迎的。 代码样式格式化
deno fmt 并按常规提交信息.
请用! 如果你有任何问题、反馈或要求,请告诉我们.
许可证
版权2024 德诺瑟尔团队. 版权所有。 麻省理工学院执照.