lyhokia
lyhokia5mo ago

How to rewrite this code so I don't have to force deno to stop linting?

import { parse } from "https://deno.land/std@0.218.2/toml/mod.ts";
import { match } from "npm:ts-pattern@5.0.8";
// suppose options.config might be either string or undefined
const readToml = match(options.config)
.with(P.string, async (configPath) => {
return parse(await Deno.readTextFile(configPath));
})
// deno-lint-ignore require-await
.with(undefined, async () => ({}))
.exhaustive();
console.log(await readToml);
import { parse } from "https://deno.land/std@0.218.2/toml/mod.ts";
import { match } from "npm:ts-pattern@5.0.8";
// suppose options.config might be either string or undefined
const readToml = match(options.config)
.with(P.string, async (configPath) => {
return parse(await Deno.readTextFile(configPath));
})
// deno-lint-ignore require-await
.with(undefined, async () => ({}))
.exhaustive();
console.log(await readToml);
So here I'm matching and generating 2 promises. However the second promise is not necessary. Is there a way I can just generate the value? I tried to remove 2 asyncs and push up the async to outer function but that doesn't seem to work because await in a nested function is not allowed.
2 Replies
Deno AI Helper
Deno AI Helper5mo ago
I wasn't able to find the answer to your question in the official Deno documentation. However, based on the code snippet you've provided, I can offer some general TypeScript advice. If you want to avoid generating an unnecessary promise for the case where options.config is undefined, you can return a value directly instead of an async function. Since match from ts-pattern is expecting all branches to return the same type (in this case, a promise), you can wrap the direct value in Promise.resolve() to match the expected return type. Here's how you could rewrite the match expression:
const readToml = match(options.config)
.with(P.string, async (configPath) => {
return parse(await Deno.readTextFile(configPath));
})
.with(undefined, () => Promise.resolve({}))
.exhaustive();
console.log(await readToml);
const readToml = match(options.config)
.with(P.string, async (configPath) => {
return parse(await Deno.readTextFile(configPath));
})
.with(undefined, () => Promise.resolve({}))
.exhaustive();
console.log(await readToml);
In this version, when options.config is undefined, it will return a resolved promise with an empty object, which should satisfy the type requirements without needing to use an async function. Please note that this advice is not based on the Deno documentation, and you should double-check the accuracy of the advice given. If you encounter further issues, you might want to consider reaching out to the community or looking into more specific resources related to ts-pattern.
lyhokia
lyhokia5mo ago
Thanks