1

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!

1
  • I'll do it in exactly the same way (btw, ES5 is subset of TypeScript so everything you write in ES5 is a valid TypeScript as well). Commented Nov 3, 2016 at 17:01

1 Answer 1

15

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.