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?

4

1 Answer

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; 
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.