You can easily verify the existence of attr3
in the object.
function fn(config: Type1 | Type2): void {
if ('attr3' in config) {
const {
attr1,
attr2,
attr3
} = config;
} else {
const {
attr1,
attr2
} = config;
}
}
Alternatively, you could utilize a custom type guard
function IsType2(config: Type1 | Type2): config is Type2 {
return (config as Type2).attr3 !== undefined;
}
function fn(config: Type1 | Type2): void {
if (IsType2(config)) {
const {
attr1,
attr2,
attr3
} = config;
} else {
const {
attr1,
attr2
} = config;
}
}
If we really only wanted to destructure once, we could create a join type, although it would involve coercing the type instead of inferring it.
function fn(config: Type1 | Type2): void {
const {
attr1,
attr2,
attr3
} = config as Type1 & Type2;
}
To my knowledge, there isn't a direct way to destructure a union type.