DEV Community

Cover image for Introduction to TypeScript πŸ‘©β€πŸ’»
Shaan Alam
Shaan Alam

Posted on

Introduction to TypeScript πŸ‘©β€πŸ’»

Hello guys, you might have probably heard the popular name "TypeScript" if you are into Web Development world. I had recetly started using TypeScript in my React Project 1-2 months back and I loved it. At first, it was difficult to code in TypeScript, but trust me, once you get the taste of TypeScript and the cool "Intelli Sense" in your code editor, you'd never want to go back to normal JavaScript. It just makes your JS development life a lot easier.

Typescript

What does it do?

TypeScript provides type definitions to your JavaScript code which makes the development process a lot faster and also helps to catch bugs easily.

Setup Typescript in your project

To include TypeScript into your project, install Typescript as a dev dependency by typing.

yarn add typescript -D
or
npm install typscript --save-dev

Now, we need ts-node. ts-node is a Node.js package used to execute TypeScript files or run TypeScript in a REPL environment.

yarn add ts-node -D
or
npm install ts-node --save-dev

We also need to generate a tsconfig.json file which has all the typescript configurations for our project. To initialise a tsconfig.json, type the following command.

npx tsc --init

You will see that a tsconfig.json file like this is generated in the root folder of your project.

tsconfig

Create a file called index.ts and paste the following code console.log('Hello world')

Now type npx ts-node index.ts in your terminal to get the output.

typescript output

If you want to compile your TypeScript code to JavaScript code type npx tsc index.ts, and you will see that a index.js file has been generated in your project.

typescript output file typescript output

TypeScript Basics

Primitive Data types

There are three primitive data types in JavaScript i.e. number, string and boolean. To create a variable with typed definition in TypeScript -

const username: string = "Shaan Alam";
const age: number = 18;
const isAdult: boolean = true;
Enter fullscreen mode Exit fullscreen mode

To provide data types to variables, you can simple define their type by adding a colon infront of the variable. However, this is not needed in this case as TypeScript will automatically infer its data type automatically.

Arrays

Arrays can be created the same way as the normal variables are created. You just have to add [] with the data type. For example, if you want to create an array of strings, you could do something like this

const names: string[] = ["Alice", "Bob", "John"];

// Similarly for numbers and booleans
const ages: number[] = [18, 19, 24];
const areAdults: boolean[] = [true, true, true];
Enter fullscreen mode Exit fullscreen mode

It is to be noted that if you have created an array using string[] data type, you could only provide string elements in the array or else typescript will throw you an error

// Not Allowed!! ❌
const names: string[] = ["Alice", "Bob", { name: "John", age: 18 }];
Enter fullscreen mode Exit fullscreen mode

Any

TypeScript also has a any data type which can be used to prevent a particular value causing type checking errors. For example, in the previous example, we could do something like this, and TypeScript won't show you an errror.

// Okay!! βœ…
const names: any[] = ["Alice", "Bob", { name: "John", age: 18 }];
Enter fullscreen mode Exit fullscreen mode

However, it is recommended not to use any data type, because it can cause bugs.
One good use case of any is that, when you don't know the type of the data before-hand, you can use any to stop showing errors.

Functions

TypeScript allows you to type your functions by typing parameters and return value.

// Typing parameters
function sumOfNumbers(a: number, b: number) {
  return a + b;
}

// Typing parameters and return value
function sumOfNumbers(a: number, b: number): number {
  return a + b;
}

sum(12, 34); // Okay βœ…
sum("190", "234"); // Wrong ❌. TypeScript won't allow this
Enter fullscreen mode Exit fullscreen mode

However, you don't always need to specify your return value explicitly, typescript is smart enough to infer the return value from the return statement itself.

typescript

Object Types

One of the most common data structures that will be using in javascript is Objects. Typescript can help you provide typed definitions to your objects as well.
If you create an object like this and hover over the user, it will show you the shape of the object, which is automatically inferred by typecript

let user = {
  fullName: "Shaan Alam",
  age: 18,
};
Enter fullscreen mode Exit fullscreen mode

typescript

You can type your objects just as you create a normal object in parenthesis and provide the object properties along with their type.

let user2: { fullName: string, age: number } = {
  fullName: "Shaan Alam",
  age: 18,
};
Enter fullscreen mode Exit fullscreen mode

Type Aliases

What if you want to use the same typed definition for different objects? Writing definitions for different objects can be quite repetitive. A type alias can help you with this.
You can create your own types using type aliases and use them.

type User = {
  fullName: string;
  age: number;
};

let user3: User = {
  fullName: "Alice",
  age: 20,
};

let user4: User = {
  fullName: "Bob",
  age: 34,
};

let user5: User = {
  fullName: "John",
  age: 35,
};
Enter fullscreen mode Exit fullscreen mode

In this example, a User type id created and used as a type definition for multiple objects having the same type of data.

You can also use Type Aliases to type functions like this.

type Sum = (a: number, b: number) => number;
const sumOfNumbers: Sum = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

Interfaces

An interface is kind of same as type except there are few differences between them. We can rewrite the above example using Interface like this.

interface User {
  fullName: string;
  age: number;
}

let user3: User = {
  fullName: "Alice",
  age: 20,
};

let user4: User = {
  fullName: "Bob",
  age: 34,
};

let user5: User = {
  fullName: "John",
  age: 35,
};
Enter fullscreen mode Exit fullscreen mode

Note - A good difference between the use case for interface and type aliases can be that you can use interface for typing objects and type aliases for other things!

Learning TypeScript at first can be tough, but trust me it pays off afterwards. Here are few resources from where you can learn TypeScript

Youtube Videos


TypeScript Docs - https://www.typescriptlang.org/docs/

Thank You!!

Find me here -
GitHub - https://github.com/shaan71845
Twitter - https://twitter.com/shaancodes
Instagram - https://instagram.com/shaancodes
LinkedIn - https://www.linkedin.com/in/shaan-alam-01784018a/

Top comments (0)