Problems with TypeScript federation types

interface ModuleA{
    width: number;
    height: number;
}

interface ModuleB{
    width: number;
    offset: number;
}

function test(params: ModuleA | ModuleB): any{
    console.log(params.offset);
}
The joint declaration in

TypeScript,
in this case, throws an error to the effect that ModuleA does not have an attribute of offset .
how to solve this problem

Mar.16,2021

in your code params can be ModuleA or ModuleB type. If you pass in a ModuleA type, there is no params.offset attribute, so it fails the check (which is why you use TypeScript), so you report an error, no doubt.

< hr >

Plan 1:

you can take a look at User-Defined Type Guards

.
interface ModuleA{
    width: number;
    height: number;
}

interface ModuleB{
    width: number;
    offset: number;
}
function isModuleA(param: ModuleA | ModuleB): param is ModuleA {
    return (<ModuleA>param).height !== undefined;
}

function test(params: ModuleA | ModuleB): any{
    if(isModuleA(params)){
    console.log(params.height);
    }else{
    console.log(params.offset);
    }
}
const foo:ModuleA={width:3,height:0};
test(foo);

scenario 2

of course, you can also add an optional offset attribute to ModuleA.

Menu