TypeScript: Getting Started
Introduction
Typescript is a superset of JavaScript that adds static typing to the language. It enables you to catch potential errors and improve code quality. In this post, we will cover the basics of TypeScript and how to get started with it.
Installation
To start using TypeScript, you need to install it. You can do so by running the following command in your terminal:
bash
npm install -g typescript
Creating a TypeScript File
To create a TypeScript file, simply save your file with a .ts
extension. For example, app.ts
.
Compiling TypeScript
To compile your TypeScript code into JavaScript, use the TypeScript compiler (tsc
). Run the following command in your terminal:
bash
tsc app.ts
Variable Declarations
In TypeScript, you can declare variables using the let
or const
keywords. Unlike JavaScript, TypeScript allows you to specify the type of the variable. For example:
typescript
let name: string = "John";
const age: number = 25;
Type Annotations
Type annotations allow you to specify the types of variables, function parameters, and return values. TypeScript uses type inference, but you can explicitly annotate types to improve readability and catch errors early. For example:
typescript
function add(num1: number, num2: number): number {
return num1 + num2;
}
Interfaces
Interfaces define the shape of an object. They can be used to enforce a structure and ensure that objects adhere to a specific contract. For example:
typescript
interface Person {
name: string;
age: number;
greet(): void;
}
Classes
Classes in TypeScript provide a blueprint for creating objects with properties and methods. You can specify access modifiers and use inheritance to create more complex structures. For example:
“`typescript
class Animal {
protected name: string;
constructor(name: string) {
this.name = name;
}
walk() {
console.log(${this.name} is walking.
);
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
bark() {
console.log(${this.name} is barking.
);
}
}
“`
Conclusion
In this post, we covered the basics of TypeScript, including installation, variable declarations, type annotations, interfaces, and classes. TypeScript offers many more features that can enhance your development experience and improve code quality. Start using TypeScript today to take advantage of its static typing capabilities.