Search code examples
typescriptfunction-parameterconditional-types

conditional function arguments in typescript


Is it possible to have a conidial required argument type based on the first argument type:

type ConditionalRequiredArg<T, P> = T extends string ? P | undefined : P;

function func<T, P>(_arg1: string | number, _arg2: ConditionalRequiredArg<T, P>) {}

func('foo'); // Error: Expected 2 arguments, but got 1.

In theory, the above function should not require a second argument, but it does!

Edit: I am aware of '?' for optional argument types, but I would like to make it conditional to leverage the compiler error and suggestions.


Solution

  • You can always use the signature overloading to screen users from directly using the implementation signature:

    function func<P>(_arg1: string, _arg2?: P)
    function func<P>(_arg1: number, _arg2: P)
    function func<P>(_arg1: string | number, _arg2?: P) { }
    

    This code forces user to choose either the first signature or the second to use, and not the third signature of the implementation.

    func('foo', 1); // success
    func('foo'); // success
    func(1, 1); // success
    func(1); // Error: Argument of type 'number' is not assignable to parameter of type 'string'