'How to restrict Typescript generic function to objects containing variadic method of a certain name and parameterization?
Honestly, I wasn't even sure how to word this question. I want to write a function that takes an object and calls a variadic method by name in such a way that typescript is checking that both the method name exists on the type and the function parameters are correct.
Bellow is not valid Typescript. I'm looking for something that is.
const thing = {
add: function(x: number, y: number) { return x + y },
inc: function(x: number) { return x + 1 },
}
function test<T extends { K: (...args: Args) => R }, K extends keyof T, Args extends any[], R>(obj: T, key: K, ...args: Args) {
return obj[key](...args)
}
test(thing, "add", 2, 2) //OK
test(thing, "inc", 2) //OK
test(thing, "foo", 2, 2) //BAD
test(thing, "add", 2, "a") //BAD
Solution 1:[1]
here's the playground
don't hesitate to ask questions if any arise
UPDATE: I managed to simplify the solution and it seems to work for all the cases now
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
