I'm having an issue converting a discriminated union into a string. The union comprises two interfaces. When I use the function with a simple object that matches one of the interfaces, I get the desired output. However, if I use a class that implements the interface, I receive `undefined`. Can someone clarify this behavior for me? Is there a workaround?
interface Foo {
kind: 'pending',
myVar: string
}
interface Bar {
kind: 'running',
myVar2: string
}
type FooBarUnion = Foo|Bar;
class FooClass implements Foo {
kind: 'pending'
myVar: string
constructor(text) {
this.myVar = text;
}
}
function fbuToString(o: FooBarUnion ) {
switch (o.kind) {
case "pending": return `Object is pending. ${o.myVar}`;
case "running": return `Object is running. ${o.myVar2}`;
}
}
// prints undefined
console.log(fbuToString(new FooClass('test')));
// prints expected result
console.log(fbuToString({kind:'pending', myVar: 'test'}));
I'm executing this file using ts-node filename.ts