Day 5 of TypeScript — As a Beginner

Things I’ve learned on day 5…

SriniWhoCodes
4 min readJun 13, 2023
Photo by Arnold Francisca on Unsplash

Things I’ve Learned Today:

  1. Practiced More By Doing Counter Project
  2. Generics

1. Practiced More By Doing Counter Project

  • I wanna know what types should I need to use for HTML Tags.
  • So I decided to do a simple Counter Project. Here’s the entire code for that! 👇
const increment: HTMLButtonElement | null =
document.querySelector(".increment");
const decrement: HTMLButtonElement | null =
document.querySelector(".decrement");
const counter: HTMLHeadingElement | null = document.querySelector("h2");

let i: number = 0;

if (increment && decrement && counter) {
increment.addEventListener("click", (): void => {
counter.textContent = `${++i}`;
});
decrement.addEventListener("click", (): void => {
counter.textContent = `${--i}`;
});
}
  • By doing this I came to know other properties for each tag in HTML! Like for Button there’s HTMLButtonElement and for Heading there’s HTMLHeadingElement and so on...
  • If you’re working on a very simple project like this, you don’t need TypeScript at all. Just like I’ve mentioned in one my previous blogs.

2. Generics

  • Let’s see a good example for this.
  • Generics in TypeScript are like a special box that can hold any type of toy.
  • Just as the box is flexible and can store different toys, generics allow us to create code that can work with different types of data.
  • Instead of writing separate code for each type, we can use generics to write reusable code that works with many types.
  • It’s like having a machine that can produce any kind of toy, without needing a separate machine for each type.
  • Generics make our code more flexible, reusable, and easier to maintain.
  • We can use generics when creating data structures or functions that need to work with different types of data.
  • They help us avoid repetition and write code that can adapt to different scenarios.
  • Here’s an example code:
// A generic function to print the contents of an array
function printArray<T>(arr: T[]): void {
for (let item of arr) {
console.log(item);
}
}

// Usage
const numbers = [1, 2, 3, 4, 5];
const names = ["Alice", "Bob", "Charlie"];

printArray(numbers); // Prints: 1 2 3 4 5
printArray(names); // Prints: Alice Bob Charlie
  • <T>: is the type which accepts any type of data for the array argument.
  • Then you might ask me this: “I can also use the `unknown` type for the arrays right? Why would I have to use This generic stuff?”.
  • That’s an important question to answer!
  • Let’s see the same code example but with Generics and without Generics (with unknown type):
// Using generics
function printArray<T>(arr: T[]): void {
for (let item of arr) {
console.log(item);
}
}

// Using unknown type
function printArrayUnknown(arr: unknown[]): void {
for (let item of arr) {
console.log(item);
}
}

// Usage
const numbers = [1, 2, 3, 4, 5];
const names = ["Alice", "Bob", "Charlie"];

printArray<number>(numbers); // Type checking and inference with generics
printArray<string>(names);

printArrayUnknown(numbers); // No type checking or inference with unknown type
printArrayUnknown(names);
  • In this example, printArray uses generics, while printArrayUnknown uses the unknown type. Let's compare their differences:

Type Safety:

  • Generics: By using generics, you specify the expected type explicitly (number or string in this case). This allows the compiler to perform type checking and inference, ensuring that only values of the specified type are passed to the function. It provides type safety and prevents potential runtime errors due to incorrect types.
  • Unknown: When using the unknown type, the compiler does not perform type checking or inference on the array elements. All elements are treated as "unknown" types, and you lose some of the type safety guarantees. You would need to manually handle type assertions or checks within your code to ensure type safety.

Type Inference:

  • Generics: With generics, the compiler infers the type based on the argument passed to the function. In our example, printArray<number>(numbers) infers that T is number, and printArray<string>(names) infers that T is string. This allows you to write more concise code without explicitly specifying the type every time.
  • Unknown: The unknown type does not provide any type inference. It treats all elements as "unknown," and you need to manually handle type assertions or checks to work with the elements.

Code Readability:

  • Generics: Using generics explicitly states the type in the function signature (printArray<T>(arr: T[])). It improves code readability by conveying the expected type to anyone using the function, making the code more self-explanatory.
  • Unknown: With the unknown type, the function signature (printArrayUnknown(arr: unknown[])) does not convey the expected type, and it may require additional comments or documentation to clarify the intended usage.

The summary of the above example and explanation is this: While both generics and the unknown type provide flexibility, generics offer stronger type safety, type inference, and improved code readability.

Generics allow you to write reusable code that works with different types, while maintaining type safety through compiler checks.

The unknown type is more flexible but sacrifices some type safety and requires manual type handling within the code.

It is generally recommended to use generics whenever possible to leverage the benefits of type safety and code clarity.

NOTE: I’ve learned only a handful of things about the generics and I’ve practiced only a bit. So make sure to research well if you’re into generics.

That’s a wrap🚀

I hope you find this blog useful. If you did then don’t forget to clap, comment, and share this blog with your friendly devs.

Bye for now…👋

Resources That I’ve Used For This Blog:

  1. YouTube video for Generics: https://youtu.be/FcOa2G9kJPE
  2. TypeScript’s Official Docs For Generics: https://www.typescriptlang.org/docs/handbook/2/generics.html

--

--

SriniWhoCodes

I write about Web Development and other related stuffs.