Angius
Angius5mo ago

Typing `parseArgs` from `@std/cli` properly

I'm having trouble figuring out how would I type the result of parseArgs with collect setting.
import { parseArgs } from "@std/cli";

const args = parseArgs(Deno.args, { collect: ["path"] });

generatePaths(params[0].toString(), args["path"]);
^^^^^^^^^^^^
import { parseArgs } from "@std/cli";

const args = parseArgs(Deno.args, { collect: ["path"] });

generatePaths(params[0].toString(), args["path"]);
^^^^^^^^^^^^
the error is caused by the function taking a { [key: string] string } as the second parameter, while args[path] is typed as unknown[]. The code works, just so we're clear, it's just the types that error out.
1 Reply
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, it seems like you're encountering a type mismatch error where args["path"] is inferred as unknown[] but your function expects a parameter of type { [key: string]: string }. One potential way to resolve this issue is to assert the type of args["path"] to the expected type. Since args["path"] is an array due to the collect option, you might need to transform it into the expected object format or adjust your function's expected parameter type to match the actual type of args["path"]. Here's a suggestion on how you might assert the type if you are certain that args["path"] will always be an array of strings:
import { parseArgs } from "@std/cli";

const args = parseArgs(Deno.args, { collect: ["path"] });

// If you are sure that args["path"] is an array of strings, you can assert it like this:
const paths = args["path"] as string[];

generatePaths(params[0].toString(), { path: paths[0] }); // Assuming you want to use the first path
import { parseArgs } from "@std/cli";

const args = parseArgs(Deno.args, { collect: ["path"] });

// If you are sure that args["path"] is an array of strings, you can assert it like this:
const paths = args["path"] as string[];

generatePaths(params[0].toString(), { path: paths[0] }); // Assuming you want to use the first path
Please note that this advice is not based on the Deno documentation, and you should double-check the accuracy of the advice given. It's important to ensure that the runtime behavior matches your expectations when using type assertions.

Did you find this page helpful?