Skip to content

Utility function to merge default options with user-defined ones.

License

Notifications You must be signed in to change notification settings

ruggeryiury/set-default-options

Repository files navigation

About

Set Default Options is a utility function to create default options for any function while merging with user-defined options that can be received as argument. The idea is to always set default values for any function that has an "option" parameter, totally avoiding undefined values to be evaluated. See the example below:

import setDefaultOptions from 'set-default-options'

// This is the interface with all the options
// that can be settled to our function.
// On this one, you can have optional values
// to use on the function argument
interface ReturnOptsFunctionOptions {
  option1?: string
  // Null values are accepted to act as a neutral value!
  option2?: string | null
}

function returnOpts(options?: ReturnOptsFunctionOptions) {
  // Call "setDefaultOptions()" to make all values required,
  // since we're setting default values for each one of them,
  // then place the "options" parameter as second argument
  // of the function to merge.

  // Remeber to put your options type as type parameter.
  const opts = setDefaultOptions<ReturnOptsFunctionOptions>(
    // Default values
    {
      option1: 'example',
      option2: null,
    },

    // Merge with the user-provided options object.
    options
  )

  // Return the new object to test.
  return opts
}

// Let's test the function!
const opts = returnOpts({ options2: 'example2' })
console.log(opts.option1) // 'example'
console.log(opts.option2) // 'example2'

API

setDefaultOptions<T>()

  • Parameters:
    • defaultOptions Required<NonNullable<T>> — The default options of the function.
    • userOptions? Partial<T> | undefinedOPTIONAL User-provided options with properties to override any default option property. If undefined or an empty object, no default properties will be merged.
  • Returns: Required<NonNullable<T>>