0

What is difference between canDeactivate1 & canDeactivate2 in below typescript interface ? How these functions will be considered ?

export interface CanComponentDeactivate
{
    canDeactivate1 : ()=> Observable<boolean> | Promise<boolean> | boolean;
    canDeactivate2 (): Observable<boolean> | Promise<boolean> | boolean;
}

How can i write same function in JavaScript ?

iamjp
  • 1
  • 4
  • second looks like a function types which should return value of any type after `:` – Sergey Jun 12 '18 at 10:17
  • It's not a function but an interface which just describes which types are taken or returned – Sergey Jun 12 '18 at 10:18
  • 1
    First one is a property whos type is either: a parameterless method that evaluates into a Observable, a boolean promise or a boolean. Second is a parameterless method that returns a value of one of the 3 possible types after `:` – Jota.Toledo Jun 12 '18 at 10:45

1 Answers1

0

The second is basically a shortcut (well, not much) for the first.

The expression ()=> Observable<boolean> | Promise<boolean> | boolean is a type declaration for a function that expects no arguments and returns an observable, a promise or a boolean. You can use such declarations anywhere a type is expected:

let foo: ()=> Observable<boolean> | Promise<boolean> | boolean;
foo = 1; //doesn't work, foo has to be a function
foo = () => 1; //doesn't work, we are not allowed to return a number
foo = () => true; // works
foo = function() { return true }; //works

Because functions on objects are usually used as methods, interfaces have a special syntax that resembles method declarations in classes. canDeactivate2 (): Observable<boolean> | Promise<boolean> | boolean looks like a method without a body, which is more in line with what other languages have.

a better oliver
  • 24,069
  • 2
  • 48
  • 59