hey guys i'd like to know how to make a callback function in typescript.
I know how to do it in 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.');});
But i can't find a way to do it with TS. you guys have an example of it?
thank you!
Typescript is a superset of javascript, so any javascript code is valid typescript code.
But you can use types for safety:
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.