繁体   English   中英

在TypeScript中将定义的函数用作参数

[英]Using defined functions as parameters in TypeScript

有什么办法可以让仅将某些功能作为参数的功能?

这就是我想做的:

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

function baz(f: foo | bar): any

我知道我可以这样做: function baz(f: (string) => string): any ,但这不是我在这里要查找的。 另外,我真的没有这个问题的目的,只是出于好奇而问。

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

function foo(str: string): string { return ""}
function baz(f: typeof foo): any {}

但是,如果您想将参数限制为仅这两个特定函数,则无法在打字稿中表达出来(打字稿通常按结构而不是按标称声明,甚至对于对象)

您也许可以使用特制品牌类型来做一些事情:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM