Reputation: 4165
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.
Upvotes: 0
Views: 74
Reputation: 2665
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();
}
}
Upvotes: 1
Reputation: 7780
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()
}
}
Upvotes: 1