Some Lesser Known TypeScript Features
Elie
Posted on February 15, 2019
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:
You can write numbers with underscores. For example,
1000000000
can be written as1_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 writing25
is more readable than2_5
.If you know a variable is defined you can add a
!
after it to access it without first checking if the value isundefined
. For example, you may be injecting props into a React component using a decorator (e.g.@inject(router)
or@inject(store)
). You can now writethis.props.store!.someValue
even if the definition of store isstore?: 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).
- 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.
- 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 dox.substr(0, 2)
it will throw a compile error. We can use an unknown variable by first doing a type check. For example, writingif (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!
Posted on February 15, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024
November 27, 2024