TypeScript: Argument Validation
Only TS Generics to rescue
We all know that over fetching db impacts performance. So we do fetch only the required fields before passing the fetched data into some function and inside the function we add basic argument validation explicitly.
The goal of this article is to show how to offload the basic argument validation on TypeScript at compile time itself.
Note: It merely removes the burden of basic argument type validation.
Let’s jump into some code example. Take a moment to read out the below code snippet.
The above code looks pretty good.
Now think, what if we can remove if(!student.dateOrBirth)
check and make TypeScript
to error out at compile time if dateOfBirth
field is missing.
Look at the solution in TypeScript way.
In the above code calculateAge()
will throw error if we forget to fetch the field from db. Ex: studentRepo.getOneById(1, {id: 1})
Explanation
I don’t think we need any explanation here. Basic TypeScript
& Generics
knowledge is enough to understand.
getOneById<T extends keyof Student>(id: number, fields: Record<T, 1> ): Pick<Student, T>
This function signature makes sure that what all the fields mentioned in the function call, same fields must be in the returned response type.
References
Generics: https://www.typescriptlang.org/docs/handbook/2/generics.html
Utility types: https://www.typescriptlang.org/docs/handbook/utility-types.html#handbook-content
keyof Operator: https://www.typescriptlang.org/docs/handbook/2/keyof-types.html