I am currently dealing with a JSON array containing serialized objects, each of which has a type
field. My challenge lies in deserializing them properly due to TypeScript not cooperating as expected:
Check out the TypeScript playground for reference.
type serializedA = { type: 'A', aProp: string };
class A {
public type = 'A';
constructor(data: serializedA) {}
}
type serializedB = { type: 'B', bProp: string };
class B {
public type = 'B'
constructor(data: serializedB) {}
}
const classMap = { A, B };
function deserialize(serializedObject: serializedA | serializedB) {
const Klass = classMap[serializedObject.type];
new Klass(serializedObject);
}
The problem arises from the last line where TypeScript is unable to determine whether Klass
and serializedObject
are now both instances of A
or B
. I'm struggling to find a way to clarify this to TypeScript.