I have two classes and a service storing data in a map with a string key to access, stored data is of type of one of these 2 classes.
class DummyObj {
constructor(public text: string, public dummy: string){}
}
class DummySecondObj {
constructor(public text: string, public dummySecond: number){}
}
type ValidTypes = DummyObj | DummySecondObj | undefined;
class ServiceClass {
private readonly storage = new Map<string, ValidTypes>();
constructor() {
this.storage.set('key1', { text: 'dummy 1', dummy: 'dummy element 1' });
this.storage.set('key2', { text: 'dummy 2', dummySecond: 4 });
this.storage.set('key3', new DummyObj('dummy 1','dummy element 1'));
this.storage.set('key4', new DummySecondObj('dummy 1', 4));
}
getData(resourceKey: string): ValidTypes {
if (this.storage.has(resourceKey)) {
const meta = this.storage.get(resourceKey);
//console.log(meta);
if (meta instanceof DummyObj) {
console.log('is DummyObj');
return (this.storage.get(resourceKey) as DummyObj);
}
else if (meta instanceof DummySecondObj) {
console.log('is DummySecondObj');
return (this.storage.get(resourceKey) as DummySecondObj);
}
else {
console.log('not found')
return undefined
}
}
return undefined;
}
}
When called the method getData I would expect that instanceof is able to see the structure equal to my class and return with the correct state but this is not true if not created with the constructor but just as inline object. There is a way to make it work also with the inline generic object initialization? And can someone point me out why exactly is it not working? thank you
const service = new ServiceClass();
var x = service.getData('key1');
var x = service.getData('key2');
var x = service.getData('key3');
var x = service.getData('key4');
Here also the running example live example
[Updated]