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.
You can define the overload of your function + change the implementation, like:
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.
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.
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
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
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 {}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.