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.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b2b219-33e39.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b2b219-33e39.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?