DEV Community

Cover image for What is TypeScript and why should you use it?
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com

What is TypeScript and why should you use it?

What is TypeScript?

TypeScript is a programming language developed and maintained by Microsoft. It introduces additional features like strict type binding (variables are bound to specific data types) to JavaScript and can also be compiled down to JavaScript as well.

TypeScript is an Open Source Project, and the source code for it is available on GitHub.

What additional features does TypeScript introduce?

TypeScript adds several additional features to JavaScript. The most important one is strict typing (it is turned on by default, but can be turned off in case the developer doesn't want to use it).

Apart from strict typing, TypeScript introduces a plethora of features like Interfaces, Mixin classes, Enums and much more, as discussed later in the article.

Why should you use TypeScript?

If the features mentioned above weren't enough to convince you to use TypeScript, the following reason would definitely do so. TypeScript overcomes the largest issue with JavaScript; which is: a problem can only be detected during runtime in JavaScript, which may result in applications with bugs being shipped to the end-user. This will affect any business negatively by hampering the user experience. TypeScript removes this problem by checking for any issue at compile time.

The following script will not raise any errors when using JavaScript, but if you use TypeScript, the compiler will point out that nonExistentProperty doesn't exist on object obj

const obj = {
    foo: "baz",
};

console.log(obj.nonExistentProperty);
Enter fullscreen mode Exit fullscreen mode

Even if you are using an editor, using TypeScript provides you with better suggestions and linting as shown below:

TypeScript Debug

JavaScript Debug

getWeatherDetails() will accept a boolean value which TypeScript points out, but JavaScript fails to do so.

Getting Started with TypeScript

Enough theoretical stuff. Now let's get our hands dirty writing our first TypeScript script.

NOTE: You will need a Node.js and a package manager (npm or yarn, in this article, we will be using npm) installed to use TypeScript locally. You may use an online compiler like typescript playground for compiling, but it is not a good idea in the case of a large project.

To install TypeScript globally (replace the -g tag with -D to add it as a dev dependency in a Node package), use the following command:

npm install -g typescript
Enter fullscreen mode Exit fullscreen mode

Now you will be able to compile any TypeScript code to JavaScript. Let's test it using a basic snippet:

const obj = {
    foo: "baz",
};

console.log(obj);
Enter fullscreen mode Exit fullscreen mode

To compile the file use (you can also use the commands without installing TypeScript by adding npx before every command):

tsc <filename>.ts
Enter fullscreen mode Exit fullscreen mode

You will find a new file <filename>.js created in the same folder, which can be run like any JavaScript file.

TypeScript vs JavaScript dilemma

Now you might come up with 2 questions:

  1. Why does the TypeScript code have to be compiled to JavaScript?
  2. If the code compiles down to JavaScript, why would we bother writing it in TypeScript?

The answer to the first question is TypeScript isn't understood by any browser, so it has to be converted to JavaScript so that browsers can execute the code.

The answer to the second question would be, same as why you should use TypeScript over JavaScript, it offers type check at compile time as opposed to runtime. If you try to compile the test.ts with the error (as shown in Why should you use TypeScript? section) the compiler would throw an error and warn you about the incorrect code.

TypeScript features

As mentioned earlier, TypeScript has several additional features compared to JavaScript, we will be going over a few of them in this section.

Type System

The default types available in TypeScript are given below:

Data Type Keyword Description
Number number Double-precision 64-bit floating-point values. It can be used to represent both, integers and fractions.
String string Represents a sequence of Unicode characters
Boolean boolean Represents logical values, true and false
Void void Used on function return types to represent non-returning functions
Null null Represents an intentional absence of an object value.
Undefined undefined Denotes value given to all uninitialized variables

TypeScript also allows you to combine 2 or more data types to create a Union

let union: number | string;

union = 10;
union = "Hello World";

// union = true // ERROR!!! `union` can only be a number or a string
Enter fullscreen mode Exit fullscreen mode

In the case of JavaScript, an error would have not been pointed out and might lead to bugs down the line.

Interfaces

TypeScript Interface allows you to describe how an object would look like, something that is not possible in JavaScript.

// Interfaces for Objects
interface IObjectDefination {
    foo: number[]; // foo is a number array
    baz: Date; // baz is a date
    [key: number]: string; // any other key (only numbers) can contain a string as its value
}

let obj: IObjectDefination;

// Interfaces for Classes
interface IClassDefination {
    data: string;
    func: () => void;
}

class Class implements IClassDefination {
    data: string;

    func() {
        return;
    }
}
Enter fullscreen mode Exit fullscreen mode

Enums

Enums allow a developer to define a set of named constants, making it easier to document intent or create a set of distinct cases.

enum Direction {
    Up,
    Down,
    Left,
    Right,
}

function move(direction: Direction) {
    // ...
}

move(Direction.Up);
move(Direction.Down);
Enter fullscreen mode Exit fullscreen mode

Achieving a similar result with JavaScript would require you to create an object with the respective keys. Even then we would not be able to specify the data type of direction in move().

const Direction = {
    Up: "Up",
    Down: "Down",
    Left: "Left",
    Right: "Right",
};
Enter fullscreen mode Exit fullscreen mode

Streamlining TypeScript compilation

Earlier we used tsc to compile a single TypeScript file. This may become a problem in the case of a large project with thousands of files. In that case, you can set up a listener to watch for changes.

For watching for changes, you need to create a tsconfig.json file in the root directory of your project and add the following:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "strict": true,
        "outDir": "dist"
    },
    "include": ["src"],
    "exclude": ["node_modules", "dist"]
}
Enter fullscreen mode Exit fullscreen mode

Alternately, you may use tsc --init to create the file (it is generated pre-configured and with all options, the unnecessary ones commented out).

Now you can set up the listener

tsc -w
Enter fullscreen mode Exit fullscreen mode

Now, any TypeScript file you create or modify in the src (tsconfig.include) folder will be compiled to JavaScript file in the dist (tsconfig.compilerOptions.outDir) folder whenever you make any changes.

NOTE: You can add the tsconfig.json to any of your Node packages and convert it from a JavaScript project to a TypeScript one.

Conclusion

In this article, we went through what TypeScript is and how it can help you write better code. We saw some features it offers and how certain features like Enums and Interfaces can make your life a little easier. Now it's time for you to add TypeScript to your very own project!

Learn Full-Stack Web Development

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.