I have a function that can take arguments of types A
or B
, which have some members in common but lack others. Within the body of the function, however, I'd like to be able to reference members that occur on only A
or only B
, with the understanding that they may be undefined at runtime.
An example looks like this:
type A = {
common: number;
a_only: string;
}
type B = {
common: number;
b_only: string;
}
type ArgType = A | B; // this doesn't actually work in the desired fashion
function takesAorB(arg: ArgType) {
if (arg.common > 1) {
// no need to check for undefined since both A and B have `common`
}
if (arg.a_only?.length) {
// the effective type of `arg.a_only` should be `string | undefined`,
// since the property exists on A but not B
}
if (arg.b_only?.length) {
// the effective type of `arg.b_only` should be `string | undefined`
// since the property exists on B but not A
}
}
I can get pretty close by doing something like this:
type ArgType = A | B | Partial<A> | Partial<B>
However, this makes every member of A
and B
optional. I would like it if the members that A
and B
have in common were still available as non-nullable. Is there any way to accomplish this?