⭐ Passing Type Arguments ⭐
In this example, we will work with the Set data structure from JavaScript.
Here we are creating a set of guitarists and adding Jimi Hendrix and Eric Clapton to it.
const guitarists = new Set();
guitarists.add("Jimi Hendrix");
guitarists.add("Eric Clapton");
We expect an error to be thrown when we try to add a non-string to the set.
However, our error is not being thrown because the guitarists set is not strictly typed as a set of strings.
We see this same issue when hovering over the guitaristsAsArray variable inside of the array test:
Hovering shows us that guitaristsAsArray is an unknown array.
We will figure out how to update guitarists to be typed a set of strings.
👉 Solution:
We can pass in a type argument to the Set to tell it what type it should be:
const guitarists = new Set<string>();
When the argument is in place, we can only add items of that specific type.
This also enables useful things like hovering over guitarists.add() and seeing that it expects a string.
✍️ Digging Deeper:
We can pass in type arguments as well as function arguments to certain functions.
In this case, since Set is a class that we are instantiating, we can command-click or right-click and say "Go to Definition".
Double-clicking takes us to a file called lib.es2015.collection.d.ts which is where certain parts of JavaScript are typed out.
There is an interface for Set that starts like this:
interface Set<T> {
That T represents the type argument.
Back in our solution code, if you erase the type argument and go back to just Set(), hovering over it will show you that it is typed as Set.
Lots of JavaScript constructs and popular libraries use this.
🫶 Another Example:
Let's create a new Map and pass a string as a type argument:
const map = new Map<string>()
Now when we hover, we see the following:
Map<any, any>
This is because Map accepts two types of arguments: the first is the key, and the second is the value.
If we wanted to create a map where the keys and values were both strings, it would look like this:
const map = new Map<string, string>()
map.set('someKey', 'someValue')
Changing someKey to a number would now give us an error.
This concept of passing type arguments to certain functions and constructors and classes is crucial for understanding TypeScript as a whole!
I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Top comments (0)