doberkofler
doberkofler

Reputation: 10341

Typescript function return type depending on number or type of arguments

Let's say I have a function that should return different types depending on the number and type of arguments. How would I describe this in TypeScript?

function foo(t: number): string
function foo(t: number, s: string): boolean {
   return typeof s === 'string' ? true : 'false';
}

In words: the function foo returns a string when invoked with a number argument and returns a boolean when invoked with a number and a string parameter.

Upvotes: 2

Views: 2246

Answers (3)

Kegulf
Kegulf

Reputation: 1

Interesting question! TypeScript don't support this as far as my experience go. What you could do is to set the return type to a this | that type. This means "return type is this or that"

function foo(t: number, s: string): string | boolean {}

In my team at work we generally try to avoid the this | that approach because it can be an added source of bugs.

My recommendation is two functions with specific return types, if this is possible in your application.

function getFoo(t: number): string {}

function isFoo(t: number, s: string): boolean {}

Upvotes: 0

Orelsanpls
Orelsanpls

Reputation: 23505

You can define the overload of your function + change the implementation, like :

Playground

function foo(t: number, s: string): boolean;

function foo(t: number): string;

function foo(t: number, s?: string): string | boolean {
   return s !== void 0 ? true : 'false';
}

const var1 = foo(50);
const var2 = foo(50, 'str');

In this way, TypeScript will be able to define which is the correct type of your variable depending on the number of parameter of your function.


enter image description here


enter image description here

Upvotes: 3

Quentin
Quentin

Reputation: 943185

TypeScript doesn't have that level of granularity. You can say:

function foo(t: number, s?: string): string | boolean

…in which it takes an optional second argument and returns either a string or a boolean, but if you want to make the return value type conditional on the arguments then you would need to define two seperate functions.

Upvotes: 0

Related Questions