Home > front end >  How to make an optional arg case generic type is void for a function in typescript
How to make an optional arg case generic type is void for a function in typescript

Time:09-28

I'm trying to create a simple function that has a generic type as default void and in this case the arg is optional, but if I provide a generic type string for example the arg is mandatory as a string.

Example:

enter image description here

Code:


function DoSomething<T = void>(arg: T extends void ? undefined : T){
    console.log(arg ?? `printing void`);
}

DoSomething(); // the arg is not required

DoSomething<string>('hello there!'); // the arg is required as string

Playground link here

CodePudding user response:

You can use an overloaded function signature. It is designed to address this kind of scenario: where more than one unique sequence of argument types are accepted by the function. The overload signature pattern also provides context-aware IntelliSense suggestions as you type:

TS Playground

function fn(): void;
function fn<T>(arg: T): void;
function fn<T>(arg?: T) {
  console.log(arg);
}

fn(); // OK

fn<string>('hello'); // OK

fn('hello'); // OK (string is inferred from the argument by the compiler)

fn<number>(100); // OK

fn<number>(); /* NOK
~~~~~~~~~~~~~
Expected 1 arguments, but got 0.(2554) */

fn<number>('hello'); /* NOK
           ~~~~~~~
Argument of type 'string' is not assignable to parameter of type 'number'.(2345) */

// etc...
  • Related