npm install -g typescript. Once that installs, thats it! TypeScript has been installed and is ready to use... BUT we still have a few things to talk about before we can get our fingers on the keys.
Having the right set up is always the first step to success with anything, and TypeScript is no different. The first thing to do is to make sure your IDE is set up for TypeScript. If you're using VS code, good news, TypeScript Support is already baked in. The next thing to do is create a
tsconfig.json file. The tsconfig file allows you to customize project settings, and acts like an object with key/value pairs. You can easily create a tsconfig by running
tsc --init in your terminal. This file will have some default options, and some roll your own options that you can add into your project as you see fit.
tsc command in your terminal. The
tsc command looks through your root directory for the
Ok, now we will really get into coding...
For each different variable that you have in your application you need to type the variable. Its super easy to do this let's check it out starting with some of the easier types.
const letsRock : boolean = true
Breaking this down is pretty simple. We declare a new variable
letsRock and then set it to equal true (because who doesn't like rocking). The big difference here is that I declared
letsRock as a boolean type. If the value of
letsRock ever equals anything except a boolean we are going to get an error.
let myAge : number = 0
let myName : string = "Phil"
the same pattern is applied to strings and numbers. You declare the variable, declare the type and then set the initial value. Thats three out of seven types down, were cooking with gas now. Let's check out some of the other types and how we can type them. This is where things get fun .
let students: string = ['Matt', 'David', 'Jake']
On the surface, this looks really scary, but take a step back and checkout whats happening. There is a variable of
students being declared, and
let students: Arrray<string> = ['Matt', 'David', 'Jake']
This should be enough to get you started with TypeScript and for you to know just enough to be dangerous. The world of TypeScript is much deeper than what we covered in this blog post, so be sure to be on the lookout for part two of this blog post.
Until next time,
Happy coding, and remember to keep that GitHub green.