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>(...)- 执行 aGET并MyResponseInterface定义 HTTP 响应的结构)。
有专门的图书馆吗?
从我在使用时看到的情况来看,@types/js-yaml它load不是通用的,这意味着它不接受类型参数。
因此,在这里获取类型的唯一方法是使用断言,例如:
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)
| 归档时间: |
|
| 查看次数: |
28069 次 |
| 最近记录: |