'VSCode Typescript param default mis-typing issue

I am making a function like this:

function myFunc({ flag1 = true } = { flag1: true }) {
  const myFlag = flag1;
}

My intention is that you can call myFunc without param. It will default to {flag1: true}, or you can passing an object to it.

But when I do myFunc({ flag1: false });, I get this warning in vscode:

(property) flag1?: true
Type 'false' is not assignable to type 'true'.ts(2322)

To get rid of this, I needed to add typing:

  function myFunc({ flag1 = true }: { flag1: boolean } = { flag1: true }) {
    const myFlag = flag1;
  }

Is this the only way go about this?



Solution 1:[1]

What about something like this:

function myFunc({ flag1 } = { flag1: true }) {
  const myFlag = flag1;
}

The flag1 will be true when using the default object.

The type definition is inferred as:

function myFunc({ flag1 }?: { flag1: boolean }): void

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Didi Bear