What is the best way to selectively pass certain values to the args object?

Is there a way in TypeScript to pass only one argument into args and have other values be default without using "args = {}" or declaring defaults within the function to avoid issues with intellisense?

function generateBrickPattern (
    wallWidth: number,
    wallHeight: number,
    args = {
  maxBrickWidth: 100,
  maxBrickHeight: 50,
  minBrickWidth:  50,
  minBrickHeight: 25
}) {}

generateBrickPattern(500,500,{maxBrickWidth: 75}) //Preferred

generateBrickPattern(500,500,{maxBrickWidth: 75, 
                              maxBrickHeight: 50,  
                              minBrickWidth:  50,
                              minBrickHeight: 25}) //Not desired

The preferred syntax generates the following error.

Argument of type '{ maxBrickWidth: number; }' is not assignable to parameter of type '{ maxBrickWidth: number; maxBrickHeight: number; minBrickWidth: number; minBrickHeight: number; }...'.

Answer №1

In order to ensure the last argument's type is defined, you should explicitly declare it instead of relying on TypeScript to infer.

Consider this approach:

interface BrickPatternConfig {
    maxWidth?: number;
    maxHeight?: number;
    minWidth?: number;
    minHeight?: number;
}

function createBrickPattern (
    wallSizeX: number,
    wallSizeY: number,
    settings: BrickPatternConfig = {
      maxWidth: 100,
      maxHeight: 50,
      minWidth: 50,
      minHeight: 25
}) {}

Alternatively, if preferred, you can directly include the configuration inline like so:

function createBrickPattern (
    wallSizeX: number,
    wallSizeY: number,
    options: {
        maxWidth?: number,
        maxHeight?: number,
        minWidth?: number,
        minHeight?: number
    } = {
        maxWidth: 100,
        maxHeight: 50,
        minWidth: 50,
        minHeight: 25
    }) {}

Answer №2

To achieve this, one approach is to utilize destructuring args with default values:

function createWallPattern (
    wallLength: number,
    wallHeight: number,
    {
        maxBrickLength: maxBrickLength = 100,
        maxBrickHeight: maxBrickHeight = 50,
        minBrickLength: minBrickLength = 50,
        minBrickHeight: minBrickHeight = 25
    } = {}
) {
    console.log(maxBrickLength);
}

If avoiding destructuring, an alternative method involves merging the provided args with the defaults as follows:

interface WallPatternOptions {
    maxBrickLength: number;
    maxBrickHeight: number;
    minBrickLength: number;
    minBrickHeight: number;
}

function createWallPattern (
    wallLength: number,
    wallHeight: number,
    args: Partial<WallPatternOptions> = {}
) {
    const options: WallPatternOptions = {
        maxBrickLength: 100,
        maxBrickHeight: 50,
        minBrickLength: 50,
        minBrickHeight: 25,
        ...args
    };

    console.log(options.maxBrickLength);
}

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

Connecting Ionic 3 with Android native code: A step-by-step guide

I just finished going through the tutorial on helpstack.io and was able to successfully set up the HelpStackExample with android native based on the instructions provided in the GitHub repository. The only issue is that my company project uses Ionic 3. H ...

If a task is currently ongoing, be sure to subscribe to it; otherwise, restart it

If I have a long-running observable called longObservable, which emits a new string once after 5 seconds and then completes. longObservable(): Subject<string> { return timer(5000).pipe{ map(() => randomString()) } } Other pages c ...

Using ThreeJS to Apply Dual Materials to a Mesh Entity

With ThreeJS, it's possible to incorporate more than one material into an Object3D/Mesh as stated in the documentation. You can either utilize a single Material or an array of Material: Class declaration and constructor for Mesh TypeScript file (exce ...

Can we access global variables directly in an Angular 2 HTML template?

After setting the app.settings as shown below public static get DateFormat(): string { return 'MM/DD/YYYY';} I need to utilize it in one of my HTML templates for a component. This is what I want to achieve. <input [(ngModel)]="Holiday" [dat ...

The parameter of type '{ userInfo: string | null; }' cannot be assigned to type 'never' in this argument

Currently, I am working on creating a context API in React using TypeScript to store user details and tokens. Since I am relatively new to TypeScript, I am facing some challenges understanding the errors below. Can someone please assist me with this? ..... ...

What is the best way to find out if an array index is within a certain distance of another index?

I'm currently developing a circular carousel feature. With an array of n items, where n is greater than 6 in my current scenario, I need to identify all items within the array that are either less than or equal to 3 positions away from a specific inde ...

The default selected item in Material Select does not function properly on the second attempt

Is there a way to reset an Angular Material Select Component to its default value after manually changing it on the UI screen? It seems to work fine during initialization but not after manual changes. I am attempting to create a button that will revert th ...

Looking to personalize the MUI - datatable's toolbar and place the pagination at the top?

I successfully managed to hide the toolbar icon, but I am struggling with positioning pagination from bottom to top. Additionally, I am attempting to add two buttons (reset and apply) in the view-Column toolbar without any success in customizing the class. ...

The issue with the tutorial is regarding the addHero function and determining the source of the new id

Whenever I need to introduce a new superhero character, I will utilize the add(string) function found in heroes/heroes.component.ts add(name: string): void { name = name.trim(); if (!name) { return; } this.heroService.addHero({ name } as H ...

Deactivate user session in LoopBack 4 API

Can anyone provide a clear example of an API endpoint for logging out that allows for deleting the token stored during login instead of relying on the web browser? It seems there is no documentation available on how LoopBack generates a default user when ...

Implementing Adsterra in your next.js or react.js project: A step-by-step guide

Currently, I am working on integrating the Adsterra Banner 300x50 into a ts/js reactjs + nextjs project. The provided script code from Adsterra is as follows: <script type="text/javascript"> atOptions = { 'key' : 'XXXXXX&a ...

What is the best way to retrieve a specific property from a JSON object in the data received from an

Currently, I am working on an AJAX call that targets this PHP file: <?php $response = array('error' => "Please provide a valid name"); echo json_encode($response) ?> Within my JavaScript file, the following code is implemented ...

Is the state variable not being properly set by using React's setState within the useCallback() hook?

Within a React FunctionComponent, I have code that follows this pattern: const MyComponent: React.FunctionComponent<ISomeInterface> = ({ someArray, someFunction }) => { const [someStateObjVar, setSomeStateObjVar] = React.useState({}); const [ ...

I find certain operations within certain types to be quite perplexing

I have defined two different types as follows: interface ChangeAction{ type: 'CHANGE' payload: string } interface DeleteAction { type: 'DELETE' payload: number } Now, I want to add a prefix to each value of the type ke ...

Locating the Smallest Value in an Array of Objects

Looking at an object with keys containing arrays of objects that each have a price value. The goal is to find and return the lowest price value. In this scenario, aiming to return the value 8. Wondering if using the reduce method would be the best approach ...

I possess a table that showcases MatIcon buttons. Upon clicking on a button, two additional buttons should appear at the bottom of the table

I am working on a table that contains mat-icon-buttons. When the button is clicked, it should display 2 additional buttons at the end of the table. Upon clicking the first button, its color changes from primary to red, and I would like to add two more butt ...

A guide on transforming JSON data to an array format where nested arrays are encapsulated within objects using curly braces instead of square brackets in TypeScript

Retrieve data from a REST API in the following format: { "ProductID":1, "Category":[ { "CategoryID":1, "SubCategory":[ { "SubCategoryID":1, } ] } ] } I need to t ...

Use a pipe to show the content of the md-input

In my Angular 2 Material application, I have a form that includes a price input: <md-input [(ngModel)]="price" placeholder="Price"> </md-input>{{price|customCurrency}} This input field uses a custom version of the CurrencyPipe which you c ...

What could be causing my "Swiper" component to malfunction in a TypeScript React project?

In my React project, I decided to incorporate the Swiper library. With multiple movie elements that I want to swipe through, I began by importing it as follows: import Swiper from 'react-id-swiper'; Utilizing it in my code like this: <div cla ...

The different types of property 'cacheLocation' do not match

I have been working on updating an old React app from JavaScript to Typescript gradually. I started by migrating the configuration file, but encountered an error when renaming it to .TS. Here is the error message: /Users/xx/yy/lulo/src/adalConfig.ts (13, ...