4 Shocking TypeScript Tricks to Exercise your Mind
Quick Tips to Improve your Code ⚡
TypeScript is a programming language full with hidden tips and tricks.
In this article, we will discuss 4 Shocking Tips I discovered while learning TypeScript.⚡
So without further ado... Let's jump right in!
1. Extracting Array Member Types
Here is a classic tip to extract every array member as a union type.
Let's take a look at the example below:
This is a very simple tip, yet under-used by the TypeScript community.
- First we get the type of the names array through
(typeof names)
- Then we index into the array using
[number]
, which gives us all the values in the array as a type.
2. TODO Type Alias
This is a very simple yet effective tip:
Here I aliased the type any
to TODO.
type TODO acts as a placeholder that you can search-and-replace globally.
Here is an example of how I would use it:
PRO TIP: In vscode, select the TODO type and press shift+alt+f12
to find all references to it in every file!
3. ElementRef (React Only)
For all the React users out there, this tip will save you a lot of time.
ElementRef<T>
is a type you import from the react package that returns a reference type based on it's name.
Here is an example:
- Here we use
ElementRef<"button">
to get the correct type for the useRef hook. - This tip works for every JSX element, e.g. audio, anchor...
4. Const Generic Parameters
To understand const Generic Parameters, lets first look at basic Generics:
Here we use the Generic Parameter Name
to represent the input and output type for this function getRandomName
.
However, even though we pass in three literal names, the return type is string
.
We want the type to be more accurate here, so let's add a const generic parameter to achieve this:
The only difference here is that we use const Name
instead of just Name
.
This lets us narrow down the type from string
to the union of the three names.
Conclusion
These were 4 Shocking TypeScript tips that should exercise your mind.⚡
I hope you found these useful, and I will write more articles like this to help you get better at TypeScript fast.
If you enjoyed this article, please make sure to Subscribe, Clap, Comment and Connect with me today! 🌐