在TypeScript中将定义的函数用作参数 [英] Using defined functions as parameters in TypeScript

查看:1165
本文介绍了在TypeScript中将定义的函数用作参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any way to have a function that only takes certain functions as parameters?

这就是我想要做的:

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

function baz(f: foo | bar): any

我知道我可以这样做:function baz(f: (string) => string): 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.

推荐答案

您可以使用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

这篇关于在TypeScript中将定义的函数用作参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆