Set type for function parameters?
Choose TypeScript for typed function parameters which can set the parameter types directly in your function. This means sound type safety.
Example:
Our function add
now strictly requires two number
parameters.
Beyond TypeScript, there are other techniques you can consider for type safety and clarity of code. Let's explore them.
Getting hands-on with Type Checking Libraries
PropTypes - your guardian angel for React
In the world of React, we rely on PropTypes
for type-checking props. Similarly, it can check the type of function parameters.
Creating your Type guards
Without a library like PropTypes, you can jump into the levitating train of custom type-checking functions:
These functions ensure runtime validations, so no more nasty surprises because of the wrong types.
Light up your code with JSDoc
JSDoc for efficient annotation
With JSDoc comments, your code talks to you about its expected types and automatically enhances the developer experience:
With IDEs such as Visual Studio Code that parse JSDoc, your development process becomes as fun as eating pie (3.1415) π₯§, providing auto-completion and type checks without screaming for TypeScript.
Destructuring - a good "first aid" for objects
When parameters are objects, destructuring shows what's really inside the box:
The destructuring ensures you understand the structure while making the code more readable.
More ways to wrangle types
Google Closure Compiler - the overseer
Not fond of TypeScript? Google Closure Compiler's type annotations feel just at home in the wild world of JavaScript:
By turning on the advanced mode of Google Closure Compiler, your JavaScript code turns into an Iron Man suit, with type safety included.
Facebook's Flow - the savior
Another savior in our type-checking crusade is Flow from Facebook:
Install Flow, run it against your code, and voila, type mismatches are now gotchas! Parentheses make sure you are doing arithmetic, not acrobatics.
Out-of-the-box Typing
Play with types
We can sometimes play with type casting when we canβt enforce a strict data type:
Ensure that the operations you want are performed on your own terms.
Boomerang with a typedFunction
You can encapsulate type-checking within a typedFunction
to keep your code neat and type-safe:
You've now rolled out a red carpet for systematic type enforcement.
Was this article helpful?