TypeScript helps us catch a particular type of problem around the use of object literals.
NOTE: this relates to using a defined type versus an object literal
function printCar(car: {
make: string;
model: string;
year: number;
chargeVoltage?: number;
}) {
// ...
}
printCar({
make: 'Tesla',
model: 'Model 3',
year: 2020,
chargeVoltage: 220,
color: 'RED', // <- ERROR: Excess Property Error
});
Error msg: "... Object literal may only specify known properties, and 'color' does not exist in type
{ make: string; model: string; year: number; chargeVoltage?: number | undefined; }
"
The possible fixes are:
- Remove the
color
property from the object - Add a
color: string
to the function argument type (can also be optional) - Create a variable to hold this value, and then pass the variable into the
printCar
function
Here's the fix using option 3:
const myTesla = {
make: 'Tesla',
model: 'Model 3',
year: 2020,
chargeVoltage: 220,
color: 'RED',
};
printCar(myTesla); // NO ERROR
The function body has no possible way to access the color
property.
If an object literal is used as the function's input then that object exists only as that input's value and no where else in the code.
If the function can't access the color
property then there's no reason for that property to exist on the object literal.
However if the input's value comes from a variable, that variable (and its color
property) might be used elsewhere in the code.
Therefore the function doesn't care if it includes extra properties...as long as it includes the properties (and types) it's requiring.
From the TypeScript Fundamentals, v3↗ course on FEM↗ taught by Mike North↗.