qiu8310
qiu8310

Reputation: 237

How to get an optional argument through generic type in typescript

I have a function like this in typescript:

function foo<P>(param: P) {
  // ...
}

I want when provide generic type P, then param should be required

foo<string>('bar')

And when not provide generic type P, then param should not be required

foo()

But in typescript, when calling foo(), ts will throw error: [ts] Expected 1 arguments, but got 0.

If I make param optional like this function foo<P>(param?: P) {}, then it will not throw error when calling foo<string>() while it should.

How can I make it work?

Upvotes: 0

Views: 1166

Answers (1)

JB Nizet
JB Nizet

Reputation: 691625

You can use function overloads:

function foo(): void;
function foo<P>(param: P): void;
function foo(param?: any) {
  // ...
}

Upvotes: 2

Related Questions