DEV Community

Elie
Elie

Posted on

Some Lesser Known TypeScript Features

In the past few years, TypeScript has become a popular way to write JavaScript apps. The language is immense and can do a lot of things.

Here’s a short list of some rarer TypeScript features you may not be aware of to help with your development:

  1. You can write numbers with underscores. For example, 1000000000 can be written as 1_000_000_000. It will be compiled to the regular number in Javascript, but using this syntax makes things easier to read. The underscores can be placed anywhere in the number although writing 25 is more readable than 2_5.

  2. If you know a variable is defined you can add a ! after it to access it without first checking if the value is undefined. For example, you may be injecting props into a React component using a decorator (e.g. @inject(router) or @inject(store)). You can now write this.props.store!.someValue even if the definition of store is store?: Store.

Be careful not to overuse this feature, but there are times where it comes in handy. You can read here for further discussion of this problem. (You could always use an if statement too, but that’s more verbose for cases you know the if statement is truthy).

  1. You can set a variable to have type never. This means it can’t be set to anything. How is this useful? One place it can be useful is to check you’ve handled every possibility of a switch statement. For example:
const someFunction = (temperature: 'hot' | 'cold' | 'warm') => {
  switch (temperature) {
    'hot': console.log("it's hot outside!"); break
    'cold': console.log("it's cold outside!"); break
    default: const x: never = temperature;
  }
}

The above code will throw a compile-time error, because x can be reached. If you add a switch case for warm with a break after it, the compile error will go away as the default block can no longer be reached.

  1. Another lesser used type you can use is unknown. This just means we have no idea what the item we have is. This may happen if we’re calling a third party API for example. If we try do x.substr(0, 2) it will throw a compile error. We can use an unknown variable by first doing a type check. For example, writing if (typeof x === “string”) x.substr(0, 2) would no longer throw an error.

No any other useful TypeScript tricks that should be included? Feel free to mention them in the comments!

Top comments (1)

Collapse
 
janpauldahlke profile image
jan paul

Nice. The ! Feature is neat.