Typescript - How to determine the real non-primitive type of an union parameter in a construcotr?

Viewed 16

I have two classes and a enum:

abstract class Base {
  protected constructor(method: EnumMethod) {
    ...
  }
}

class Leaf {
  constructor(method: EnumMethod) {
     super(method);
  }
}

enum EnumMethod {
  CARD = 'card',
  APPLEPAY = 'applePay',
  GOOGLEPAY  = 'googlePay',
}

Then, I want the Leaf class can accept more options while the old codes passing in EumMethod directly still can work, so I create an interface for it:

interface Params {
  method: EnumMethod;
  foo: string;
  bar: number;
}

Then I find I don't know how to determine the parameter in constructor. What I want to do is:

class Leaf {
  constructor(params: EnumMethod | Params) {
     super(params is EnumMethod ? params : params.method);
  }
}

How can I implement the is operator in TypeScript?

0 Answers
Related