TypeScript in 5 Minutes: A Concise Introduction with Practical Examples

Feri Lukmansyah
2 min readApr 1, 2024

--

Photo by Mohammad Rahmani on Unsplash

Welcome to a quick journey into the world of TypeScript! In just 5 minutes, we’ll introduce you to the basics of TypeScript, complete with practical examples to help you grasp the concepts quickly.

What is TypeScript?

TypeScript is a statically typed superset of JavaScript that adds optional static typing and other features to the language. It aims to make JavaScript development more robust and scalable by providing features like interfaces, classes, and modules.

Getting Started

Let’s dive in with a simple example to illustrate TypeScript’s power. Suppose you have a JavaScript function that calculates the area of a rectangle:

function calculateArea(width, height) {
return width * height;
}

To convert this to TypeScript, add type annotations:

function calculateArea(width: number, height: number): number {
return width * height;
}

Now, TypeScript will enforce that width and height parameters must be numbers, and the function must return a number.

Type Annotations

Type annotations in TypeScript allow you to explicitly specify the types of variables, parameters, and return values. Let’s see an example:

let name: string = "TypeScript";
let age: number = 5;
let isAwesome: boolean = true;

function greet(name: string): string {
return `Hello, ${name}!`;
}

Here, we define variables name, age, and isAwesome with their respective types. We also have a function greet that takes a name parameter of type string and returns a string.

Interfaces

Interfaces are a powerful feature in TypeScript for defining object shapes. Consider the following interface for representing a Person:

interface Person {
name: string;
age: number;
email?: string;
}

Here, name and age are required properties, while email is optional. You can then create objects that conform to this interface:

let user: Person = {
name: "John",
age: 30,
email: "john@example.com"
};

Conclusion

In just a few minutes, we’ve covered the fundamentals of TypeScript, including type annotations, interfaces, and basic syntax. This is just the beginning of your TypeScript journey.

TypeScript offers many features to enhance your JavaScript development experience, such as classes, enums, generics, and more. As you continue your TypeScript journey, be sure to explore the official TypeScript Handbook for comprehensive documentation and examples.

Happy coding with TypeScript! 🚀

--

--