Just diving into the world of TypeScript, I am attempting to implement type-checking for a function that has an optional third argument. Depending on another parameter, this third argument may or may not be utilized.
I have designated it as optional but encountered some issues:
- An error is triggered.
- Even if the error doesn't occur, I am curious if there is a way to dynamically switch the required/optional status of the parameter
trailer
based on another parameter (vehicleType
).
Here's a sample code snippet I put together to demonstrate my dilemma:
enum VehicleType {
Car,
Pickup
}
type Vehicle = {
weight: number;
length: number;
};
type Trailer = {
weight: number;
length: number;
};
function vehicle(
vehicleType: VehicleType,
vehicle: Vehicle,
trailer?: Trailer
) {
switch (vehicleType) {
case VehicleType.Car:
return `${vehicle.length} ${vehicle.weight}`;
case VehicleType.Pickup:
return `${vehicle.length + trailer.length} ${
vehicle.weight + trailer?.weight
}`;
}
}
Running this code results in the same error cropping up twice:
Object is possibly 'undefined'. For
trailer.
object
Is there a method to instruct the compiler to mandate the presence of trailer
if the type is Pickup
, and disregard it when the type is Car
?