Skip to content
Advertisement

Typescript optional object argument craziness

so I am trying to make a object parameter optional, with optional props, and have a default value at the same time:

const myfunc = ({ stop = false }: { stop?: boolean } = { stop: false }) => {
    // do stuff with "stop"
}

this works fine, but notice that crazy function definition!

Any way to not repeat so much code?

Advertisement

Answer

I would probably write this like this:

interface MyFuncOptions {
  stop: boolean;
}
const myFunc = (options: Partial<MyFuncOptions> = {}) => {
  const defaultOptions: MyFuncOptions = {
    stop: false,
  };
  const finalOptions = {
    ...defaultOptions,
    ...options
  }
  const { stop } = finalOptions;
  // ...
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement