Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  83] [ 5]  / answers: 1 / hits: 18808  / 3 Years ago, wed, june 23, 2021, 12:00:00

I have the following yaml file:


trainingPhrases:
- help me
- what to do
- how to play
- help

I readi it from disk using readFile from node and parse it using load from js-yaml:


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

const phrases = load(await readFile(filepath, "utf8")).trainingPhrases as string[];

I get the following eslint warning:


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

Instead of suppressing the warning, I would like to map it into a concrete type for the YAML file (as it happens in axios for example: axios.get<MyResponseInterface>(...) - performs a GET and MyResponseInterface defines the structure of the HTTP response).


Is there a dedicated library for that?


More From » typescript

 Answers
558

From what I can see when using @types/js-yaml is that load is not generic, meaning it does not accept a type parameter.


So the only way to get a type here is to use an assertion, for example:


const yaml = load(await readFile(filepath, "utf8")) as YourType;
const phrases = yaml.trainingPhrases;

Or in short:


const phrases = (load(await readFile(filepath, "utf8")) as YourType).trainingPhrases;



If you absolutely want a generic function, you can easily wrap the original, like:


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

export const load = <T = ReturnType<typeof original>>(...args: Parameters<typeof original>): T => load(...args);

And then you can use it as:


const phrases = load<YourType>('....').trainingPhrases;

[#50253] Saturday, May 22, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kennedysaraiw

Total Points: 552
Total Questions: 99
Total Answers: 109

Location: South Sudan
Member since Sun, Jul 11, 2021
3 Years ago
;