1

In PHP we can check it like following. See here

interface IInterface
{
}

class TheClass implements IInterface
{
}

$cls = new TheClass();
if ($cls instanceof IInterface) {
    echo "yes";
}

Same way I want to check it in Typescript. I have done like this.

public handle() {

        return (err: any, req: Request, res: Response, next: any) => {

            switch (err.constructor) {

                case MyException:
                    var response = err.getResponse();
                    res.status(500).send(response);
                    break;
                default:
                    res.status(500).send(err.message);

            }
        }
 }

Instead of MyException I want to check IMyException. How can I do this?

Kiren S
  • 3,037
  • 7
  • 41
  • 69
  • *Instead of MyException I want to check IMyException* - what is the reasoning behind this, by the way? This may affect how the case should be handled. – Estus Flask May 09 '18 at 11:28
  • If I use the another class "YourException" which implements "IMyException", then I have to explicitly check the instance. If I use interface type checking we dont need to change the code. – Kiren S May 09 '18 at 11:33
  • 1
    Yes, it won't be an instance of this class then. You have to duck-type it like usually it's done in JS (not TS). – Estus Flask May 09 '18 at 11:38

2 Answers2

2

That is not possible in TypeScript because interfaces only exist at compile time.

Wilgert
  • 706
  • 1
  • 6
  • 23
2

Interfaces don't exist at runtime. TypeScript interfaces only guarantee structural compatibility. Class instance that is supposed to conform a type (e.g. err: MyException) shouldn't necessarily be an instance of the class of the same name (prototypically inherit from it).

In order for an interface to be used at runtime, it should be a class. If a class isn't supposed to be instantiated for some reason, it should be abstract, and concrete class should inherit from it:

abstract class BaseMyException {
  ...
}

class MyException extends BaseMyException {}

Then it can be asserted to be an instance of this class with err instanceof BaseMyException. Notice that err.constructor checks only own constructor.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565