Issue
i have recently picked up Typescript because it seemed interesting. I have used generics in C# before and managed to do quiet a few things with generics in Typescript but now im stumped for the following use case:
I have a generic function that takes in any number of Rest arguments. These arguments are than passed to a callback function which is also provided. But i cannot seem to figure out how to make the typescript compiler accept the types i provide to implicitly be passed into the callback function.
async SampleFunction(
cb: () => void,
...args: any[]
)
with this as sample usage:
let stringVariable = "lorem";
let numberVariable = 8;
SampleFunction(
(stringArg, numberArg) => {},
stringVariable,
numberVariable,
)
This example results in arguments that think they are implicitly type 'any'.
my question hereby is: how can i make this function definition so that i could pass in any aditional arguments which then get their type passed into the callback function as they are passed in the same order.
Solution
Thanks to the help of @Etheryte i got onto the right search track.
I found the sollution i wanted which is:
function SampleFunction<T extends any[]>(
cb: (...args: T) => void,
...args: T
): void {}
let stringVariable = 'lorem';
let numberVariable = 8;
SampleFunction(
(a, b) => {},
stringVariable,
numberVariable
);
This implicitly passes the right argument types from the function into the callback
Answered By - jetenergy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.