Search code examples
typescriptobjectargumentsintellisenseargs

How do I pass only some values into args object?


Is there a way to only pass in one argument into args and let other values be default in TypeScript? I dont want "args = {}" and declaring defaults within the function due to intellisense.

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

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

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

The prefered syntax gives the following error.

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


Solution

  • You can do this by destructuring args with default values:

    function generateBrickPattern (
        wallWidth: number,
        wallHeight: number,
        {
            maxBrickWidth: maxBrickWidth = 100,
            maxBrickHeight: maxBrickHeight = 50,
            minBrickWidth: minBrickWidth = 50,
            minBrickHeight: minBrickHeight = 25
        } = {}
    ) {
        console.log(maxBrickWidth);
    }
    

    If you don't want to destructure you could merge the provided args with the defaults like this:

    interface BrickPatternOptions {
        maxBrickWidth: number;
        maxBrickHeight: number;
        minBrickWidth: number;
        minBrickHeight: number;
    }
    
    function generateBrickPattern (
        wallWidth: number,
        wallHeight: number,
        args: Partial<BrickPatternOptions> = {}
    ) {
        const options: BrickPatternOptions = {
            maxBrickWidth: 100,
            maxBrickHeight: 50,
            minBrickWidth: 50,
            minBrickHeight: 25,
            ...args
        };
    
        console.log(options.maxBrickWidth);
    }