In the previous blog, we discuss some cool features of typescript. Let's continue our journey with typescript.
Typescript automatically contains special types for every DOM element.
Let's look at the example:
In the above example, typescript assigns special types to the variable based on the DOM element it signifies. This means whenever we use buttonTag variable, typescript knows all of the properties and methods associated with that type.
But what if we access the element using className or ID???
Now in this case, when we hover over the variable it says it is of type Element and do not point out to any specific HTML Element because the class can be applied to any different element in the HTML page, so typescript is not able to recognize its exact type.
So for this, we can use something known as Type Assertions.
Type assertion allows you to set the type of a value and tell the compiler not to infer it.
So in our case, we can use type assertions using the keyword as to indicate a more specific type:
const header = document.querySelector('.mainHeader') as HTMLDivElement;
Now instead of storing it as Element type, it uses HTMLDivElement type.
- Type assertions are removed by the compiler and won’t affect the runtime behavior of your code.
There is one more method to use Type Assertions using angle-bracket syntax:
const header = <HTMLDivElement>document.querySelector('.mainHeader');
A tuple type is another sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions.
Tuple is another built-in type that is a little bit like an array but with one major difference. In tuple, the types of data in each position are fixed once it's been initialized.
Let's dive into an example for a better understanding that how tuple is different from Array:
As you can see in the above code snippet, data variable can have a mixed type of string | number. And we could reset the first position from type string to number. Which is OK in the case of Arrays. Any position in the above array can be of type string or number.
In tuples, once we defined a certain position being a certain type then we cannot change that type in that position.
That's all for this article. We'll explore more new features of typescript in the next post.
Thank you for your time!! Let's connect to learn and grow together.