Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript Is it possible to distinct generic argument void?

A function has generic type argument.

When context is void, I want to input 0 arguments, otherwise I want to input 1 argument.

If I used as context: Context | void in function argument, Even when I need to add context, But I can add void type.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

is there any way to input 0 argument or check whether it is typed as void?

class TestClass<Context = void> {
  protected context : Context

  constructor(context: Context) {
    this.context = context;
  }
}

export function genericVoidNeedArgument<Context = void>(
  context: Context,
) {
  // can check type..?
  return new TestClass(context);
}

type UserType = {
  id: string
  // and so on..
};

// expected : o, real : error
// An argument for 'context' was not provided.
genericVoidNeedArgument();

// expected : error, real : error
genericVoidNeedArgument<UserType>();

// expected : o, real : o
genericVoidNeedArgument<UserType>({id: "123"});

>Solution :

You can use Function Overloads to do that.

class TestClass<Context = void> {
  protected context: Context;

  constructor(context: Context) {
    this.context = context;
  }
}

function genericVoidNeedArgument(): TestClass<void>;

function genericVoidNeedArgument<Context>(
  context: Context
): TestClass<Context>;

function genericVoidNeedArgument(context?: any): any {
  return new TestClass(context);
}

type UserType = {
  id: string;
};

genericVoidNeedArgument();
genericVoidNeedArgument<UserType>({id: "123"});
genericVoidNeedArgument<UserType>();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -> Expected 1 arguments, but got 0.

TypeScript Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading