Leverage the power of yargs in your Typescript projects

Whenever I try to abstract the options to a variable (or import them from another file), Typescript gives me this error:

Argument of type '{ exclude: { type: string; required: boolean; description: string; default: never[]; alias: string; }; someOtherFlag: { type: string; required: boolean; description: string; default: never[]; }; }' is not assignable to parameter of type '{ [key: string]: Options; }'.
  Property 'exclude' is incompatible with index signature.
    Type '{ type: string; required: boolean; description: string; default: never[]; alias: string; }' is not assignable to type 'Options'.
      Types of property 'type' are incompatible.
        Type 'string' is not assignable to type '"string" | "number" | "boolean" | "array" | "count" | undefined'.ts(2345)
import * as yargs from 'yargs';

const options = {
  exclude: {
    type: 'array',
    required: false,
    description: 'Files to exclude',
    default: [],
    alias: 'e'
  },
  someOtherFlag: {
    type: 'array',
    required: false,
    description: 'Another example flag'
    default: []
  }
};

// triggers Typescript error
const cliOptions = yargs.options(options).argv;

Answer №1

Try one of the following methods (the first method uses as const):

const options = {...} as const 

// or 
const options = {
  exclude: { type: "array"  as "array", ...},
  someOtherFlag: { type: "array" as "array", ...}
} 

Explanation:

The options object passed to yargs.options(options) may appear correct based on its declaration.

However, there is a crucial issue causing it not to work in its current state: the type of the options object gets widened. As a result, type: 'array' gets interpreted as type: string. Since yargs.options requires a string literal for the type, an error occurs.

This widening of types occurs due to an immutability check and the absence of an explicit type definition. For further information on this subject, feel free to explore the provided link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extract the initial sentence or the opening 50 words from a data object in Typescript/JavaScript

Is there a way to extract only the initial line or first 50 words from the data retrieved by the API and store it in a variable? In the HTML File: <td *ngIf="customizedColumns?.details_of_non_conformity?.value"> <span [ngCl ...

Assign a default value to empty elements in an array

Here is an example of fetching data in an array: [ { "Id": 111, "Name": "Test 1", "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8de8e0ece4e1bccde9e2e0ece4e3a3e3e8f9">[email protect ...

How can you sort an array in Typescript without considering letter case?

I am attempting to alphabetize an array in TypeScript without regard to case sensitivity. In JavaScript, this could be achieved with list.sort(function (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); }); In TypeScript, the s ...

What is the best way to determine which variable holds the greatest value in Angular?

I am working with different array lengths stored in variables and trying to determine which variable is the greatest, then change the font color of that variable. However, I encountered an issue where if two variables have the same value, only one is being ...

Modifying the @input value in the child component does not seem to reflect the changes in the parent component

parent component class export class Parent { display: boolean = false; constructor() { } displayChildComponent() { this.display = true; } } parent component template <child [isVisible]="display"></child> child component ...

Using TypeScript conditional types with extends keyof allows for checking against specific keys, but it does not grant the ability

In TypeScript, I created custom types using template literal types to dynamically type the getters and setters of fields. The types are structured like this (Playground Link): export type Getters<T> = { [K in `get${Capitalize<keyof T & strin ...

Issue: Generated fewer hooks than anticipated. This situation could be a result of an unintentional premature return statement

view image description see image here I encountered an issue while trying to retrieve a specific item from my customer list on the first attempt. The strange behavior occurs when I search for a name not present in the table, then search for an existing en ...

Adding images in real-time

I am currently working on an Angular application where I need to assign unique images to each button. Here is the HTML code snippet: <div *ngFor="let item of myItems"> <button class="custom-button"><img src="../../assets/img/flower.png ...

Downloading a PDF in a Next.js application

How can I add a button or link that will instantly download my PDF portfolio when clicked? I am currently working on my resume section and would like to provide users with the option to easily download my CV. Is there a way to do this, and if so, how can ...

An exception is thrown by TypeScript's readline.createInterface function

My current project involves creating an electron app. I am facing an issue in the main.ts file where I have constructed a seemingly simple class with a constructor that is not running as expected. The problem arises when the call to readline.createInterfac ...

Encountering a cloning error while using React Typescript and React Router DOM when calling props.history.push

When using props.history.push without passing state, everything works perfectly fine. However, when trying to pass data with state, an error occurs. The error message reads: DOMException: Failed to execute 'pushState' on 'History': func ...

How to manually resolve a type by its string or name in Angular 2

I'm facing a challenge. Is it possible to resolve a component manually with just its name known? Let's say I have a string variable that holds the name of a component, like "UserService". I've been exploring Injector and came across method ...

Edge is experiencing a slowdown when utilizing ng-bind-html

I've been using ng-bind-html to bind HTML content to a div element. However, when I attempt to bind larger amounts of HTML, it can take around 5-6 seconds for the content to load. Interestingly, this issue seems to only occur in Chrome browser. I have ...

Angular 2: Issue with disabled functionality not functioning correctly

In my TypeScript code, I have created a boolean variable called readOnlyMode. When this variable is set to true, all elements should be disabled. To achieve this, I am using [disabled]="readOnlyMode" in the HTML for elements that need to be disabled. Howev ...

Create a specific definition for a packaged item with limited access

As I worked with a package that lacked types, I took the initiative to create a type definition for it. The specific package in question is react-date-range. In order to accommodate this new type definition, I established a directory where it could be loca ...

What are the benefits of using one state in React with useState compared to having multiple states?

Is it more beneficial to optimize and enhance code readability in React using Hooks and Functional components by utilizing a single setState hook or having multiple hooks per component? To further elaborate, let's consider the following: When workin ...

What is the significance of utilizing generic types as values within a generic class?

Why is the compiler giving an error for the following code T' only refers to a type, but is being used as a value here: class Factory<T> { create(TCreator: (new () => T)): T { return new TCreator(); } test(json: string) ...

What is the best method for showcasing this console.log information in an Angular application?

I have developed a feature that displays users who are online. While it works perfectly in the console log, I am struggling to show p as the result if the user is online. Below is the code snippet: ngOnInit() { this.socket.emit('online', { r ...

State not being updated by ngrx forms 8 reducer

I am currently utilizing ngrx-forms with the ngrx 8 syntax to sync my form and state store. The actions for updating the form state are being dispatched successfully, like so: { controlId: 'adForm.location.community', value: 'wst', ...

Retrieving JSON data through HttpClient in Angular 7

I am attempting to retrieve information from this specific URL. The data obtained from this URL is in JSON format. This particular file is named data.services.ts: import { Injectable } from '@angular/core'; import { HttpClient } from '@an ...