This is one post that is part of a series of posts about what I learned building and running an application with Node.js and Typescript. To be exact the application consists of two separated codebases. One for the frontend and one for the backend. In this post I’m going to focus on the things I learned related to developing in Typescript/Javascript. There will be more posts about Tools, DevOps and Reliability.
Disclaimer: some of the lessons apply to plain javascript of course and would come up without typescript too.
Types are not checked at runtime
Interfaces, parameter types and function return types are all super helpful when developing your application. But be mindful where your data is coming from. Even if you write hello(name: string), another script can still pass in hello(1), typescript won’t check that.
Fat arrows => awesome
While developing both the backend and the frontend with TypeScript I really learned to love the fat arrow functions. I recommend this article by Brandon Morelli that shows the different syntax options for fat arrow functions and what the differences are. The main things to keep in mind:
- () Parenthesis are not required if there is only one argument
- If {} is not present around the function body, the function will return the result of the first (and only) statement
- To explicitly state a type in Typescript, () are necessary
The advantages of using fat arrows:
- In plain Javascript, I’m always asking myself “what exactly is this? right now”. With fat arrow functions, this is always what I expect it to be.
- Shorter syntax
- It’s easy to use functional paradigms, chain methods and write pure functions.
- they make your code much more readable when chaining with other higher order funcions like .map or .filter
Just consider how readable this is:
Constructor assignments are cool too
In typescript you can save yourself a lot of typing when you use constructor assignments. Just add private or public in front of an argument and it will be available as a local variable on the class. These two examples are equal:
Have a look at the available compiler options
TypeScript is very flexible and lets you adjust a lot of the strictness that you want to maintain in your application. Here are some features that we played with and decided to turn on:
{
"forceConsistentCasingInFileNames": true,
"alwaysStrict": true,
"noImplicitThis": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noEmit": true,
"noImplicitAny": true,
}