I have a script written in JavaScript that I am currently converting to TypeScript. The code I am working with includes the following:
const shapes = [];
shapes.push({ name: 'Circle', radius: 12 });
shapes.push({ name: 'Rectangle', width: 34, height: 56 });
...
To enhance type safety, I have implemented the following interfaces:
interface Shape {
name: string;
}
interface Circle extends Shape {
radius: number;
}
interface Rectangle extends Shape {
width: number;
height: number;
}
In an attempt to make the code more type checked, I initially tried this approach:
const shapes: Shape[] = [];
shapes.push({ name: 'Circle', radius: 12 } as Circle);
shapes.push({ name: 'Rectangle', width: 34, height: 56 } as Rectangle);
...
The issue with using as Type
syntax is that it does not provide full type checking. I encounter problems like the one where the 'height' property is missing but the line still passes:
shapes.push({ name: 'Rectangle', width: 34 } as Rectangle);
I found a workaround by defining the object outside the function call, which helped catch errors like missing properties:
const r: Rectangle = { name: 'Rectangle', width: 34 }; // ERROR: missing height (Yay!)
shapes.push(r);
However, this approach results in messy code due to the lengthy list of shapes.
Are there any alternatives to using as Type
for casting object literals to types inline that offer full type checking when used as parameters in functions?
PS: I am not interested in refactoring the code right now; I just want to explore other options besides as Type
for achieving complete type checking with object literals passed as function parameters. This example may not directly relate to my current code, but it serves to illustrate the problem.