在 TypeScript 中可以将强类型函数作为参数吗? [英] Are strongly-typed functions as parameters possible in TypeScript?

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

问题描述

在 TypeScript 中,我可以将函数的参数声明为函数类型.是否有一种我缺少的类型安全"的方法来做到这一点?例如,考虑这个:

In TypeScript, I can declare a parameter of a function as a type Function. Is there a "type-safe" way of doing this that I am missing? For example, consider this:

class Foo {
    save(callback: Function) : void {
        //Do the save
        var result : number = 42; //We get a number from the save operation
        //Can I at compile-time ensure the callback accepts a single parameter of type number somehow?
        callback(result);
    }
}

var foo = new Foo();
var callback = (result: string) : void => {
    alert(result);
}
foo.save(callback);

保存回调不是类型安全的,我给它一个回调函数,其中函数的参数是一个字符串,但我传递了一个数字,并且编译没有错误.我可以在保存类型安全的函数中设置结果参数吗?

The save callback is not type safe, I am giving it a callback function where the function's parameter is a string but I am passing it a number, and compiles with no errors. Can I make the result parameter in save a type-safe function?

TL;DR 版本:在 TypeScript 中是否有等效的 .NET 委托?

TL;DR version: is there an equivalent of a .NET delegate in TypeScript?

推荐答案

好的.一个函数的 type 由它的类型组成参数及其返回类型.这里我们指定callback参数的类型必须是接受数字并返回类型any的函数":

Sure. A function's type consists of the types of its argument and its return type. Here we specify that the callback parameter's type must be "function that accepts a number and returns type any":

class Foo {
    save(callback: (n: number) => any) : void {
        callback(42);
    }
}
var foo = new Foo();

var strCallback = (result: string) : void => {
    alert(result);
}
var numCallback = (result: number) : void => {
    alert(result.toString());
}

foo.save(strCallback); // not OK
foo.save(numCallback); // OK

如果需要,您可以定义一个类型别名 封装这个:

If you want, you can define a type alias to encapsulate this:

type NumberCallback = (n: number) => any;

class Foo {
    // Equivalent
    save(callback: NumberCallback) : void {
        callback(42);
    }
}

这篇关于在 TypeScript 中可以将强类型函数作为参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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