0

I have two classes ClassA and ClassB as follow:

interface IClassA {
   functionA: ()=> void
}

class ClassA implements IClassA{
  functionA(){
    console.log('hello world A')
  }
}


interface IClassB {
   functionB: ()=> void
} 

class ClassB implements IClassB{
  functionB() {
    console.log('hello world B')
  }
}

I have another function that needs to takes an instance of ClassA or ClassB as parameter as shown below.

function sayHello(object) {
   // ...
}

How can I type the object in to access to the function functionA or functionB depending on the instance of the class being use? The code below won’t work:

function sayHello(object: IClassA | IClassB) 

I don't want to use the generic any type. Thanks.

enter image description here

2 Answers 2

1

You can check for functionA in the object before trying to invoke it.

Example (playground):

function sayHello(obj: IClassA | IClassB) {
  if ('functionA' in obj) {
    obj.functionA()
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Union Types

You can actually use the | operator to create a union type. If your classes have separate logic, you can use the instanceOf syntax to check your class before running class specific code.

function sayHello(input: ClassA | ClassB) : string {
  if (input instanceof ClassA) {
    input.A();
  }
}

3 Comments

I'm getting Property 'functionA' does not exist on type 'ClassA | ClassB'. Property 'functionA' does not exist on type 'ClassB'
@lomse I've updated my answer as well. Please take a look.
Yeah this looks great. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.