I have a method that can receive multiple types of functions. I have a specific function constant
in my application, and I want to prohibit any functions from being passed whose signature matches it – without modifying the method parameter type.
I attempt to do this using instanceof
const constant = (number) => number
class Context {
execute(fn: (...args?: any) => any) {
if (fn instanceof constant)
return false
}
}
but find that the instanceof
operation is apparently not supported between functions.
What techniques are available to check during runtime if a function has the same signature as another function, in TypeScript?
Note that "in TypeScript" does not mean I require a solution that is only possible in TypeScript. Vanilla JavaScript approaches are acceptable too, if there is no way for TS to make it nicer.
2
Answers
Well you must understand that when you talk about runtime you already omit Typescript. So as an example you can check the pattern of the function as string. But its quite Dirty way. I would question what are you trying to achieve because if you use TS then it may be not the best idea to run dynamic functions. But anyways, here is how your resulted js should look like.
Here is TS version
You can’t do that check at runtime because typings are only available at compile time. However you can add a constraint with a conditional type so that any functions of type
const constant: (number: number) => number
are rejected using the typenever
.TypeScript Playground