I have a JSON array of serialized objects that each have a type field. I'm trying to deserialize them but can't get TS to play along:
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 issue is that last line. TS doesn't know that Klass and serializedObject are now either both A or both B, and I'm having trouble figuring out how to tell it that.
Klassisnew (serializedA & serlializedB) => A | Bwhich reduces tonew (never) => A | Bsince the type{type: 'A' & 'B', aProp: string, bProp: string}must be empty. This is definitely annoying since you know better, but you have to either use a type assertion or write a series of tests that narrow the type to its individual possibilities.