How to setup a new Project in Typescript
Why is Typescript so popular?
let i = "1"; let j = i + 10; console.log(j); // Returns 110
Since we have given
i as a string, when we try to add to it, we are adding strings together, not numbers. As you can see, this can become a problem.
By being strict about how we define types, typescript helps us to avoid bugs that would appear because of situations like this. This doesn't just apply to numbers and strings, but also objects, where we might expect a property. In typescript, we can force that object to always contain that property.
How to use Typescript
It should be noted at this point that typescript is a server side language, so it goes hand in hand with Node.JS. To install typescript, we use npm. Make sure you have NPM and Node.JS installed prior to this. To install typescript, run the following command:
npm i -g typescript
Now we have typescript installed, we can get to work. I've created a new folder, used
cd in the command line to move into it, and initiated both git and npm with the following commands:
git init npm init
Next, let's initate typescript for this project:
npx tsc --init
This will create a tsconfig.json file, which will hold all the information on your typescript configuration. You can edit this if you need to. I have created two folders as well - build, and dist, so my folder looks something like this:
What do these folders mean?
- build - this is where all our typescript will go.
Writing your first typescript
First off, to ensure we are writing to the right folder, update your tsconfig.json file to include the following two lines:
// .... "outDir": "dist", "rootDir": "build", // ....
This will ensure we write to the right folder, when we compile our typescript. Within build, create a new file called index.ts. Now you can start writing typescript. I have created a very basic example for index.ts:
let i:number = 1; let j:number = 2; let z:number = 3;
Now, when we want to compile our typescript, we just have to run the following command in our base directory:
Now our index.ts file will be compiled into index.js, which we'll be able to find in our dist folder.
Since running the build command constantly can be quite annoying, we can set up a typescript watcher which will compile our typescript every time we save it. To do that, we just have to run the following command:
Now all your typescript will autocompile. Now that we've done all that, you have a fully fledged typescript project, which can easily be compiled into a distribution folder, for you to easily use.
More Tips and Tricks for Typescript
- Typescript Tuples, and how they work
- How the TypeScript Record Type Works
- How the TypeScript Readonly Type Works
- How the TypeScript Exclude Type Works
- How the TypeScript Partial Type Works
- How the TypeScript Pick Type works
- How the TypeScript NonNullable Type Works
- Type Casting in TypeScript
- How the TypeScript Omit Type works
- How TypeScript Default Parameters Work