Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
7
rated 0 times [  8] [ 1]  / answers: 1 / hits: 16416  / 8 Years ago, thu, november 3, 2016, 12:00:00

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.nnIt 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!


More From » web

 Answers
115

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.nnIt 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'


(code in playground)


[#60194] Tuesday, November 1, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raymondd

Total Points: 620
Total Questions: 112
Total Answers: 94

Location: Namibia
Member since Mon, Feb 21, 2022
2 Years ago
;