Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript typescript-创建回调函数_Javascript_Web_Typescript - Fatal编程技术网

Javascript typescript-创建回调函数

Javascript typescript-创建回调函数,javascript,web,typescript,Javascript,Web,Typescript,嘿,伙计们,我想知道如何在typescript中创建回调函数 我知道如何在vanilla JS中实现这一点: function mySandwich(param1, param2, callback) { alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2); callback();} mySandwich('ham', 'cheese', function() { alert('Finished e

嘿,伙计们,我想知道如何在typescript中创建回调函数

我知道如何在vanilla JS中实现这一点:

function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
callback();}

mySandwich('ham', 'cheese', function() {
alert('Finished eating my sandwich.');});
但是我找不到一种方法来做TS。 你们有这样的例子吗


谢谢大家!

Typescript是javascript的超集,因此任何javascript代码都是有效的Typescript代码

但为了安全起见,您可以使用类型:

function mySandwich(param1: string, param2: string, callback: () => void) {
    alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
    callback();
}

mySandwich('ham', 'cheese', function() {
    alert('Finished eating my sandwich.');
});

mySandwich('ham'); // Error: Supplied parameters do not match any signature of call target

mySandwich('ham', 'cheese', (num: number) => 4 * num); // Error: Argument of type '(num: number) => number' is not assignable to parameter of type '() => void'

()

类型脚本是javascript的超集,因此任何javascript代码都是有效的类型脚本代码

但为了安全起见,您可以使用类型:

function mySandwich(param1: string, param2: string, callback: () => void) {
    alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
    callback();
}

mySandwich('ham', 'cheese', function() {
    alert('Finished eating my sandwich.');
});

mySandwich('ham'); // Error: Supplied parameters do not match any signature of call target

mySandwich('ham', 'cheese', (num: number) => 4 * num); // Error: Argument of type '(num: number) => number' is not assignable to parameter of type '() => void'

()

我会用完全相同的方法来做(顺便说一句,ES5是TypeScript的子集,所以在ES5中编写的所有内容都是有效的TypeScript)。我会用完全相同的方法来做(顺便说一句,ES5是TypeScript的子集,所以在ES5中编写的所有内容都是有效的TypeScript)。