type ShapeA = {
id: number;
length: string;
width: string;
height: string;
}
type ShapeB = {
id: number;
side1: string;
side2: string;
side3: string;
}
type Shapes = (ShapeA | ShapeB)[]
type MappedShape = {
id: number;
dimension1: string;
dimension2: string;
dimension3: string;
}
type MapFunction = (shape: Shapes) => MappedShape[];
const mapShapeA: MapFunction = (shape: ShapeA[]) => shape.map(item => ({
id: item.id,
dimension1: item.length,
dimension2: item.width,
dimension3: item.height
}));
const mapShapeB: MapFunction = (shape: ShapeB[]) => shape.map(item => ({
id: item.id,
dimension1: item.side1,
dimension2: item.side2,
dimension3: item.side3
}));
While working on the above example, I encountered an issue with TypeScript not recognizing the compatibility between ShapeA and ShapeB in both functions, even though I provided the objects explicitly. It seems like TypeScript should be able to differentiate between the two objects when needed.
Type 'Shapes' is not assignable to type 'ShapeA[]'. Type 'ShapeA | ShapeB' is not assignable to type 'ShapeA'. Type 'ShapeB' is missing properties such as length, width, and height from type 'ShapeA'.
What is a more appropriate TypeScript approach to solving this problem? I believe there may be a misunderstanding on my part regarding unions.
If I were to pass both objects as arguments to the functions, it might work by adding checks for the keys to be returned. However, this could become messy if handling a large number of objects for mapping.