DEV Community

Pan Chasinga
Pan Chasinga

Posted on

Getting Started with TypeScript in 5 Minutes

Most programming languages are like products. They either die because not enough users adopt them or they get used (and pounded at a lot).

Most of the time, it is the friction that is high for people to adopt, or the value proposition isn't 10x better or just not worth closing the learning gap.

TypeScript's value proposition

I spent 50% less time reading and understanding the code and 90% less time fixing runtime errors compared to JavaScript, and 100% of those errors came from my deliberately coercing a type to any type to fit into my lazy JS mind. Sure, it may not sound like a 10x improvement, but hear the next one out...

It's FREE and easy to switch

Since anyone can comprehend the FREE part, I'm going to give you the minimal step to switch/get started that's so easy anyone can do in less than 5 minutes.

  • Build a node project with npm init
  • Intall TypeScript with npm install -D typescript
  • Create a file name tsconfig.json and copy the following and paste in it:

{
    "compileOnSave": true,
    "compilerOptions": {
        "outDir": "./build",
        "allowJs": true,
        "checkJs": true,
        "target": "es6",
        "moduleResolution": "node",
        "module": "commonjs",
        "esModuleInterop": true,
        "sourceMap": true
    },
    "include": [
        "./src/**/*"
    ],
    "exclude": [
        "node_modules"
    ],
  "lib": ["es2015"]
}

Enter fullscreen mode Exit fullscreen mode
  • Create a src/index.ts in the project root directory and write your first TypeScript code in it:

import foo from 'bar'; // Now you can use new import syntax.


interface Greeter {
  name: string;
  greet: (string) => void;
}


class BasicGreeter {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  greet(who: string) {
    console.log(`Hello, ${who}. My name is ${this.name}`);
  }
}

function getGreeterName(greeter: Greeter): string {
  // You can be sure a Greeter always has a name.
  return greeter.name;
}

Enter fullscreen mode Exit fullscreen mode
  • Compile the Typescript with ./node_modules/.bin/tsc. You can find the compiled JavaScript in ./build/src/index.js.

There you go, you have just built a new TypeScript project in less than 5 minutes.

Top comments (0)