Using defined functions as parameters in TypeScript

…衆ロ難τιáo~ 提交于 2020-01-06 14:54:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!