The code snippet below is causing errors:
class Base { }
class Child1 extends Base {
child1Fn() {}
static deserialize(bytes: Uint8Array): Child1 {
return new Child1();
}
}
class Child2 extends Base {
child2Fn() {}
static deserialize(bytes: Uint8Array): Child2 {
return new Child2();
}
}
const childMap = {
"child1": Child1.deserialize,
"child2": Child2.deserialize
}
function deserialize<T>(
data: { name: string, bytes: Uint8Array },
deserializeMap: Record<string, (bytes: Uint8Array) => T>
): T {
const deserializeFn = deserializeMap[data.name];
if (deserializeFn) {
return deserializeFn(data.bytes)
}
}
function deserializeChildMap(data: { name: string, bytes: Uint8Array }) {
return deserialize(data, childMap)
}
An error is encountered:
Argument of type '{ "child1": (bytes: Uint8Array) => Child1; "child2": (bytes: Uint8Array) => Child2; }' is not assignable to parameter of type 'Record<string, (bytes: Uint8Array) => Child1>'.
Property '"child2"' is incompatible with index signature.
Type '(bytes: Uint8Array) => Child2' is not assignable to type '(bytes: Uint8Array) => Child1'.
Property 'child1Fn' is missing in type 'Child2' but required in type 'Child1'.
The issue arises when trying to resolve the type T
to be the first return value in childMap (Child1). The desired outcome is for T
to be resolved to Child1 | Child2
. Is there a way to achieve this?