使用定义的函数作为TypeScript中的参数

使用定义的函数作为TypeScript中的参数,typescript,function,parameters,Typescript,Function,Parameters,有没有办法让函数只接受某些函数作为参数 这就是我想做的: function foo(str: string): string function bar(str: string): string function baz(f: foo | bar): any 我知道我可以这样做:函数baz(f:(string)=>string):任何,但这并不是我在这里想要的。另外,我对这个问题也没有真正的目的,只是出于好奇而问。您可以使用typeof将特定函数的签名作为参数重新用于另一个函数 functio

有没有办法让函数只接受某些函数作为参数

这就是我想做的:

function foo(str: string): string
function bar(str: string): string

function baz(f: foo | bar): any

我知道我可以这样做:
函数baz(f:(string)=>string):任何
,但这并不是我在这里想要的。另外,我对这个问题也没有真正的目的,只是出于好奇而问。

您可以使用
typeof
将特定函数的签名作为参数重新用于另一个函数

function foo(str: string): string { return ""}
function baz(f: typeof foo): any {}
但是,如果您想将参数仅限于这两个特定函数,则无法在typescript中表达这一点(typescript通常按结构而不是名义声明,即使对于对象也是如此)

您可能可以使用特制的品牌类型来执行某些操作:

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
function createBrandedFunction any>(fn:T,brand:()=>B):T&{u brand:B}{
返回fn(如有)
}
const foo=createBrandedFunction(
函数(str:string):字符串{return”“},
()=>class{private p:any}//我们只是使用一个带有私有字段的类来确保品牌与其他任何东西不兼容
常数条=createBrandedFunction(
函数(str:string):字符串{return”“},
()=>class{private p:any}//即使是具有相同private的类也不兼容
函数baz(f:typeof foo):任意{}
baz(foo)//好的
baz(bar)//错误
baz((s)=>“”)//错误

使用Typescript 3.4.3,我在
foo
bar
的赋值中得到一个错误。错误表示“导出的类表达式的属性“p”可能不是私有的或受保护的。ts(4094)”。如果我删除
private
此错误将被删除,但是
baz(bar)
将被接受,并且不会引发任何错误。代码只是从您的示例中复制和粘贴的。@Picci如果启用了声明生成,则类表达式可能会出现此错误。你可以使用一个普通的类,或者使用其他的东西,比如brandgreat,我实际上已经声明了true。将其切换为false将删除错误,并使编译器在
baz(bar)
上检测错误。如果我尝试使用常规类,例如
类A{p:any}
类B{p:any}
,我不会让编译器检测错误。