I've got the following example code:
type GetMultipleFunction1 = () => Promise<string[]>;
type GetMultipleFunction2 = (data: number) => Promise<string[]>;
type GetMultipleFunction = GetMultipleFunction1 | GetMultipleFunction2;
function test(func: GetMultipleFunction): Promise<string[]> {
return func();
}
function getStrings(data: number): Promise<string[]> {
return new Promise(function (resolve, reject) {
resolve(['hello', 'hi']);
}) }
test(getStrings);
Why do I get the error (line 6 on return func()):
Expected 1 arguments, but got 0.
I feel like GetMultipleFunction can be of either type 1 or type 2. Type 1 needs no arguments.
How do I need to change my code to get rid of the warning?
--
Edit: What I want to achieve:
I basically want a function that accepts a function as an argument. In my example test. And it should accept a function with an argument and a function without an argument. Is that even possible?
Code example:
type GetMultipleFunction1 = () => string[];
type GetMultipleFunction2 = (data: number) => string[];
export type GetMultipleFunction = GetMultipleFunction1 | GetMultipleFunction2;
function test(func: GetMultipleFunction, data?: number): string[] {
if (data) return func(data);
return func() // here should be no warning
}
function getStrings1(data: number): string[] {
return [`hello-${data}`, 'hi'];
}
function getStrings2(): string[] {
return ['hello', 'hi']
}
test(getStrings1, 2);
test(getStrings2);
--
More specific explanation of what I want to achieve: I'm using Vue3 composition functions in order to extract Get requests. Usually I can just call: /api/groups/, but sometimes I need to pass an argument to my get request function: /api/groups/3/members/ Now number 3 would be needed to be passed as an argument.
dataoptionaltest? Right now it looks to me like the error is perfectly valid: You're callingfunc, but not passing in the data thatfuncneeds. So the two possible ways to fix it are to 1) pass in the data it needs, or 2) rewrite things so that it doesn't need data. But i don't know how to advise you on that since i don't understand the purpose of the code.dataoptional ingetStringsas well typescriptlang.org/play?#code/…