[英]Read strongly typed yaml file in Typescript?
我有以下yaml
文件:
trainingPhrases:
- help me
- what to do
- how to play
- help
我使用来自 node 的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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.