Leveraging TypeScript for Type Safety
Convert a small JavaScript snippet to TypeScript to illustrate how static typing can help catch errors at compile time and enhance code quality.
function calculateArea(shape: { width: number; height: number }): number {
return shape.width * shape.height;
}
Defines a TypeScript function that calculates the area of a shape by multiplying its width and height. The shape parameter is an object with strictly typed properties width and height as numbers, ensuring that incorrect types will result in a compile-time error.
// Trying to call calculateArea with incorrect types
const area = calculateArea({ width: '20', height: 10 });
Attempts to call calculateArea with incorrect parameter types. In this case, the width property is passed as a string, which is not allowed because TypeScript expects a number. This will cause a TypeScript error at compile time.
// Correct usage of calculateArea
const correctArea = calculateArea({ width: 20, height: 10 });
Demonstrates the correct usage of the calculateArea function by passing an object with the proper number types for both width and height. This will not cause any TypeScript errors and will compile successfully.