在Typescript中,是否可以从现有对象声明“类型”?

6

假设我有一个像这样的函数:

function plus(a: number, b: number) { return a + b }

当然,它的类型在Typescript中是(a: number, b: number) => number,表示它是一个函数。
如果我想在不真正声明其类型的情况下将此函数用作另一个函数的“参数”,我可以使用默认参数技巧:
function wrap(fn = plus) { ... }

如果我不想让它成为默认参数,我除了明确声明其类型之外还有其他选择吗?

简而言之,我不想要这个 function wrap(fn: (a: number, b: number) => number) { ... },但我希望像这样得到一些东西 function wrap(fn: like(plus)) { ... }

2个回答

10
感谢 @OweR ReLoaDeD,type fn = typeof plus 是一条有效的语句,因此这个可以正常工作:
function plus(a: number, b: number) { return a + b }
function wrap(fn: typeof plus) { }

5

关于使用泛型:

function plus(a: number, b: number) { return a + b }

function wrap<T extends Function>(fn: T) {
    fn();
}

// Works 
var wrappedPlus = wrap<typeof plus>(plus);

// Error: Argument of type '5' is not assignable to parameter of type '(a: number, b: number) => number'.
var wrappedPlus = wrap<typeof plus>(5);

// Error: Argument of type '5' is not assignable to parameter of type 'Function'.
var wrappedPlus = wrap(5);

function concat(a: string, b: string) { return a + b }

// Error: Argument of type '(a: number, b: number) => number' is not assignable to parameter of type '(a: string, b: string) => string'.
var wrappedPlus = wrap<typeof concat>(plus);

1
刚刚意识到 type fn = typeof plus 是一个有效的语句。我过于简化了问题,实际上我想使用一个高阶函数,而在这种情况下,我不认为 typeof 仍然适用。顺便说一下,非常感谢你。 - Phizaz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接