我有以下yaml
文件:
trainingPhrases:
- help me
- what to do
- how to play
- help
我使用来自节点的readFile
从磁盘读取它,并使用来自js-yaml
:的load
解析它
import { load } from "js-yaml";
import { readFile } from "fs/promises";
const phrases = load(await readFile(filepath, "utf8")).trainingPhrases as string[];
我收到以下eslint
警告:
ESLint: Unsafe member access .trainingPhrases on an any value.(@typescript-eslint/no-unsafe-member-access)
我不想抑制警告,而是想将其映射到YAML文件的具体类型中(例如在axios中发生的情况:axios.get<MyResponseInterface>(...)
-执行GET
,MyResponseInterface
定义HTTP响应的结构(。
有专门的图书馆吗?
在使用@types/js-yaml
时,我可以看到load
不是泛型的,这意味着它不接受类型参数。
因此,在这里获得类型的唯一方法是使用断言,例如:
const yaml = load(await readFile(filepath, "utf8")) as YourType;
const phrases = yaml.trainingPhrases;
简而言之:
const phrases = (load(await readFile(filepath, "utf8")) as YourType).trainingPhrases;
如果你绝对想要一个通用函数,你可以很容易地包装原始函数,比如:
import {load as original} from 'js-yaml';
export const load = <T = ReturnType<typeof original>>(...args: Parameters<typeof original>): T => load(...args);
然后您可以将其用作:
const phrases = load<YourType>('....').trainingPhrases;