Had*_*hin 0 javascript web 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.');});
Run Code Online (Sandbox Code Playgroud)
但我找不到用TS做的方法.你们有一个例子吗?
谢谢!
Typescript是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'
Run Code Online (Sandbox Code Playgroud)
(游乐场代码)
归档时间: |
|
查看次数: |
6003 次 |
最近记录: |