Skip to content Skip to sidebar Skip to footer

Optional Deconstruction Function Parameter

How do you modify the function below to make the second parameter optional? TypeScript: function getName(name: string, { lastName }: { lastName: string }) { // ... }

Solution 1:

You will need to define the interface for the lastName property as optional when defining the options object. If no options is defined, the default object is an empty object {}.

function foo(required: string, options: { lastName?: string } = {}) {
    console.log(required);
    if (options.lastName) {
        console.log(options.lastName);
    }
}

foo('foo1')
foo('foo2', {})
foo('foo3', {lastName: 'bar'})

Running the above, the console output is:

foo1
foo2
foo3
bar

See TypeScript playground link to try it out yourself.

Solution 2:

options = {} should work?

function getName(name: string, options = {}) {}

Post a Comment for "Optional Deconstruction Function Parameter"