Pablo R.
Pablo R.

Reputation: 723

Typescript callbacks

Is it possible to create callbacks in typescripts Java's way?

interface Callback () {
   OnSuccess()
   OnError()
}


doSomething("whatever", "we need", new Callback {
   Onsuccess(){

   }

   OnError () {

   }
})

or there is betters ways to get this? Thanks for any help.

Upvotes: 1

Views: 603

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249546

Sure you can do something similar in typescript:

interface Callback {
    OnSuccess(): void
    OnError(): void
}

function doSomething(s: string, s2: string, cb: Callback) {
    if (s == s2) {
        cb.OnSuccess();
    } else {
        cb.OnError();
    }
}

doSomething("whatever", "we need", { // Object literal implementing the interface (structure determines compatibility)
    OnSuccess() {

    },
    OnError() {

    }
})

Upvotes: 2

Related Questions