Home > Software design >  How do I write in typescript that I can combine function arguments at will and get hints about their
How do I write in typescript that I can combine function arguments at will and get hints about their

Time:10-03

How to DEFINE a function that takes 4 arguments (one required, three optional), can combine the arguments at will, and can be prompted for the corresponding type

function name ( url,params:type ){}
function name ( url,params:type,config:ConfigType ){}
function name ( url,params:type,config:ConfigType,option:OptionType ){}

name('http',{params}) ||
name('http',{config})  || 
name('http',{option })   ||
name('http',{params}, {option }) ||
name('http',{config}, {option }) ||
name('http',{params}, {config})

What I can think of so far is overloading functions, but there are too many parameters to combine. Is there a better solution

CodePudding user response:

type Params = {
 type?: /* ... */;
 config?: /* ... */;
 options?: /* ... */; 
}

function name (url: string, params?: Params ){
  // ...
}

The params are optional, and so are its fields. So you can call your function like:

name('http',{params})
name('http',{config})
name('http',{option})
name('http',{params, option})
name('http',{config, option})
name('http',{config, params})
name('http',{})
name('http')

CodePudding user response:

Considering that type parameters are the same in this variadic function, function overloads are not required, the parameters can be made optional:

function name (url: string, params?: Type, config?: SomeType, option?: AnotherType){...}

It's often impractical to rely on optional parameters because this requires to maintain their order and requires to use IDE hints for correct parameter values. Since named arguments are missing in JavaScript, in this case it's more practical to use a single parameters object with optional keys, with the help of destructuring and object literal shorthands:

function name (
  { url, params, config, option }: {
    url: string,
    params?: Type,
    config?: SomeType,
    option?: AnotherType
  }
){...}

Which is called like:

name({ url: 'http', params, config })
  • Related