Search code examples
javascriptangulartypescriptrxjsngrx

Typescript function parameters


I'm encountering a scenario where I have many functions with similar parameters and struggling to find a solution to make everything easily maintainable. Take the following example:

public func1(param1: string, param2: string, param3: string){}
public func2(param1: string, param2: string, param3: string){}
public func3(param1: string, param2: string, param3: string){}

public func4(param1: string, param2: string, param3: string, param4: string){}
public func5(param1: string, param2: string, param3: string, param4: string){}
public func6(param1: string, param2: string, param3: string, param4: string){}

... Etc

Initially I was thinking about an interface such as:

interface IMyInterface {
  param1: string;
  param2: string;
  param3: string;
}

and using it in the fuction:

public func1(args: IMyInaterface) {

}

But then in fuction 4,5,6 I can't really extend it to accept N number of additional args without creating new interfaces and I don't want to maintain all the derived interfaces.

I'd also like to keep my typings (not all parameters are strings and all functions have a defined number of parameters) so something like

func1(...args: string){}

wouldn't work

Any Idea how best to go about this?


Solution

  • in function 4,5,6 I can't really extend it to accept N number of additional args without creating new interfaces

    Actually, you could use an intersection type to extend an interface "inline":

    interface BaseArgs {
        foo:string, 
        bar: number
    }
    
    function func1(a: BaseArgs) {}
    function func2(a: BaseArgs & {more: boolean}) {}
    
    func1({foo: "aa", bar: 3}) // ok
    func2({foo: "aa", bar:3, more: true}) // ok