问题
Is there any way to have a function that only takes certain functions as parameters?
This is what I want to do:
function foo(str: string): string
function bar(str: string): string
function baz(f: foo | bar): any
I know I could do this: function baz(f: (string) => string): any, but that's not quite what I'm looking for here. Also, I don't really have a purpose for this question, just asking out of curiosity.
回答1:
You can reuse the signature of a specific function as a parameter to another function using typeof
function foo(str: string): string { return ""}
function baz(f: typeof foo): any {}
But if you want to limit the parameter to just those two specific function, there is no way to express that in typescript (typescript generally goes by structure not by nominal declarations even for objects)
You might be able to do something using specially crafted branded types:
function createBrandedFunction<T, B extends new(...a: any[]) => any>(fn: T, brand: ()=> B) : T & { __brand: B } {
return fn as any
}
const foo = createBrandedFunction(
function (str: string): string { return ""},
()=> class { private p: any}) // we just use a class with a private field to make sure the brand is incompatible with anything else
const bar = createBrandedFunction(
function (str: string): string { return ""},
()=> class { private p: any}) // even a class with the same private is not compatible
function baz(f: typeof foo): any {}
baz(foo) // ok
baz(bar) // err
baz((s)=> "") // err
来源:https://stackoverflow.com/questions/55600170/using-defined-functions-as-parameters-in-typescript