I have been writing TypeScript code for around 2 years now. I thought to share some special things I used in codes I wrote.
Let’s jump into the tips and tricks section!
Intersection and Union
There are situations where we need to pass different types of variables with the same parameter of a function and also where we need to combine properties of multiple variable types.
Union: Helpful when a specific function parameter supports multiple variable types.
Intersection: Merges two variable types into a single type which will have all the properties of given variable types.
If there are several variables and there is a need to set the truthy value to another variable, it could be simply solved using a couple of if conditions. But how about using
|| instead for more cleaner and wise code?
We all are familiar with abstract classes because we often use that concept to achieve well maintainable code using object oriented design principles. TypeScript supports abstract properties as well therefore we are able to define some abstract properties in a non-concrete class and use it via assigning some value in a concrete class.
External library definitions
Some TypeScript projects may use non-typescript global libraries. Our old friend Jquery is a good example. If the particular external library has TypeScript definitions there will be no issues with transpilation. Whereas if the particular external library is a custom one or not openly available one you can get away from transpilation errors using following tips.
The lazy way
Nothing but declaring the whole external library as any. For an example declaring
$ of Jquery as
declare let $: any
The active way
More correct way is to create your own TypeScript definitions for the external library (if it’s not publicly available). Simply create
index.d.ts with the required definitions using interfaces or namespaces. For a simple example Typescript definitions of Neutralinojs can be found here
Your simple if condition could be wrong
Developers mostly use
if(!variable) to check whether a particular variable is available to use it or not. Importantly
In the above example,
if condition is not behaving correctly because
itemIndex could be
0 too. Therefore if we modify the condition right to be on the point like
if(item.itemIndex != null) everything will start behaving correctly as we expected.
Happy coding everyone!😎