Hadrien Delphin Hadrien Delphin - 29 days ago 8
TypeScript Question

typescript - create a callback function

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!

Answer

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'

(code in playground)

Comments