在 Typescript 中读取强类型 yaml 文件?

pix*_*xel 6 javascript yaml types typescript

我有以下yaml文件:

trainingPhrases:
- help me
- what to do
- how to play
- help
Run Code Online (Sandbox Code Playgroud)

我使用 from node 从磁盘读取它并使用fromreadFile解析它:loadjs-yaml

import { load } from "js-yaml";
import { readFile } from "fs/promises";

const phrases = load(await readFile(filepath, "utf8")).trainingPhrases as string[];
Run Code Online (Sandbox Code Playgroud)

我收到以下eslint警告:

ESLint: Unsafe member access .trainingPhrases on an any value.(@typescript-eslint/no-unsafe-member-access)
Run Code Online (Sandbox Code Playgroud)

我不想抑制警告,而是想将其映射到 YAML 文件的具体类型(例如在 axios 中发生的情况:axios.get<MyResponseInterface>(...)- 执行 aGETMyResponseInterface定义 HTTP 响应的结构)。

有专门的图书馆吗?

Yos*_*shi 9

从我在使用时看到的情况来看,@types/js-yamlload不是通用的,这意味着它不接受类型参数。

因此,在这里获取类型的唯一方法是使用断言,例如:

const yaml = load(await readFile(filepath, "utf8")) as YourType;
const phrases = yaml.trainingPhrases;
Run Code Online (Sandbox Code Playgroud)

或者简而言之:

const phrases = (load(await readFile(filepath, "utf8")) as YourType).trainingPhrases;
Run Code Online (Sandbox Code Playgroud)

如果您绝对想要一个通用函数,您可以轻松包装原始函数,例如:

import {load as original} from 'js-yaml';

export const load = <T = ReturnType<typeof original>>(...args: Parameters<typeof original>): T => load(...args);
Run Code Online (Sandbox Code Playgroud)

然后您可以将其用作:

const phrases = load<YourType>('....').trainingPhrases;
Run Code Online (Sandbox Code Playgroud)

  • 不,我不。但我认为这不相关。无论如何,类型的一致性不能也不会在运行时被“验证”(就像 axios 一样)。因此,即使使用泛型的方法也可能只会传递该类型,因此该方法具有“可配置”返回类型。最后,这意味着您有责任,此时使用类型断言是完全有效的。 (4认同)