Part 1 of 3 TypeScript Tricks I wish I knew when I started learning TypeScript

Trick 1:

I noticed the message 'unexpected any' when using eslint with TypeScript. It made me wonder why 'any' is considered bad. How should I declare a variable that can hold any possible value? Let's examine an example.

const someArray: Array<any> = [];

// add some values
someArray.push(1);
someArray.push("Hello");
someArray.push({ age: 42 });
someArray.push(null);

We're constructing an array capable of containing all possible types. Although it may not be the most optimal code, let's proceed with it. We're including a number, a string, and an object. Now, let's examine the following code and check its outcome.

const someArray: Array<any> = [];

// ... adding the values
someArray.forEach(entry => {
  console.log(entry.age);
})

This code is considered valid TypeScript and compiles successfully. However, it will encounter a runtime failure. The reason being, when we iterate over an entry that is nullor undefined, and subsequently attempt to access the .age property, it will result in an error being thrown, as exemplified by the following message:

Uncaught TypeError: Cannot read properties of null.

I think this is some kind of false security because you expect things to just work. After all the TS compiler told you the code is fine.

But we can fix this! And the change is actually super simple. Instead of typing the array as Arraywe can just use Array if we now use the same code but with that change it will look like this.

const someArray: Array<unknown> = [];

// ... adding the values

someArray.forEach(entry => {
  console.log(entry.age);
})

and this code will not compile! Instead, TypeScript shows the following error when we try to access entry.age

using unknown enforces us to check the type (or explicitly casting the value) before we do something with a value with is unknown. Let's look at an example:

// ... other code

type Human = { name: string, age: number };

someArray.forEach(entry => {
  // if it's an object, we know it's a Human
  if(typeof entry === 'object'){
    console.log((entry as Human).age);
  }
})

In this case we checked whether the value is an object and then access the .age property. And because this is such a abstract topic, here is a little wrap-up:

any is basically saying the TypeScript compiler to not check that bit of code. Avoid using any whenever you can! It's better to use unknown instead because it enforces you to check the type of the value before using it or else it won't compile!

For more interesting content visit below website

https://fullstackindepth.com/