I implement TypeScript within AWS Lambdas, where input objects can vary. To ensure that all required fields are present in the input, I have to validate and provide a clear error message specifying any missing fields. If all necessary fields are provided, I then convert the object into a domain object outlined by an interface. Below is an example demonstrating this process:
interface Car {
wheels: string
doors: string
engine: string
}
export const checkIfCar = (maybeCar: Partial<Car>): Car | { error: string } => {
if (maybeCar.wheels == null) {
return { error: 'Car should have wheels' };
} else {
if (maybeCar.doors == null) {
return { error: 'Car should have doors' };
} else {
if (maybeCar.engine == null) {
return { error: 'Car should have an engine' }
} else {
const car: Car = {
wheels: maybeCar.wheels,
doors: maybeCar.doors,
engine: maybeCar.engine
}
return car
}
}
}
}
Although functional, the current method involves significant nesting and redundancy. Is there a more concise TypeScript-native approach to achieve the same functionality? Alternatively, is there a library available that streamlines this pattern? This seems to be a common challenge faced not only by myself.
I am familiar with User defined type guards, but maintaining these guards for each new field added may lead to oversight. Besides, it doesn't effectively address identifying missing fields. I seek a solution that automatically verifies the existence of all object fields.