Given an instance of type A or B, I want to implement a unified function that accepts a parameter of type A or B and returns its wrapped argument. Here is an example:
type A = { name: string };
type B = A[];
type DucktypedA = { // we don't care about the structure of this type as we can differentiate between A and B
a: A,
};
type DucktypedB = {
b: B,
}
function test(arg: A | B): DucktypedA | DucktypedB {
if (arg instanceof A) {
return { a: arg };
} else {
return { b: arg };
}
}
My question is, can this be achieved in TypeScript?
const a = { name: "me" };
const wrappedA = test(a); // --> { a: { name: "me" } }
const b = [{ name: "me" }];
const wrappedB = test(b); // --> { b: [{ name: "me" }] }