TypeScript — A Fancier Way to Write Your JavaScript Code

Olesya Miller
3 min readMay 2, 2021

Hi guys! I’m happy to announce that I have started learning Nest.js — a Node.js framework. As you might have heard already, TypeScript is a little more sophisticated way of writing JavaScript code, and when using Nest.js it is recommended to use TypeScript syntax instead of vanilla syntax. So this post is going to be about TypeScript! Let’s get started!

With TypeScript you can validate your JavaScript code ahead of time with static type checking. JavaScript is a dynamic language where we can do a lot of cool things. The code is interpreted by a browser but if your code is broken you will not catch it till runtime when the browser throws an error. TypeScript prevents errors like this from ever happening by extending JavaScript with types. TypeScript files have a .ts extention however you can still write plain JavaScript in them if you prefer with all of its extra features being completely optional.

TypeScript behaves like a compile language and gives us instant feedback, for example highlighting a variable that doesn’t exist. Instead of fixing this issue weeks later, after a company has lost thousands of dollars, we can fix it right here right now. The reason we get this instant feedback is because TypeScript behaves like a compile language where JavaScript is a compilation target. You can run the TypeScript compiler using tsc index.ts command. It will take a .ts file and transpile it into vanilla JavaScript. Your TypeScript project will likely have a tsconfig.json file which provides infinite number of ways to customize the behavior of the compiler.

But the primary goal of TypeScript is to enable static typing, and the way to achieve that is by annotating your code with types. We do that by following the declared variable by the colon and it’s type. That’s known as explicit type

let appName: string = "My App"

If we try to assign that variable value as wrong type we get an error

let appName: string = 5 //error

Alternatively after setting an initial value it will implicitly give the value a type. However there may be cases when you wan to change your variable’s behavior. In that case you just have to annotate your variable with ‘any’ type

let appName: any = "My App"

In addition, you can define your own custom types and interfaces which is especially powerful when working with objects

interface Pet {
age: number,
breed: string,
vaccinated: boolean,
gender: string
}

The Pet interface here defines various types of the properties on an object. We can then apply interface to a plain JavaScript object

let myPet = PetPet.age // by typing that we get autocomplete of the datatype of the property right away

We don’t have to jump back and forth to documentation to figure out why our code is not working. How cool is that?

All right, this is all for today guys.

Happy coding!

--

--