Getting Started with TypeScript: A Beginner’s Guide

MontaF - Sept. 12, 2024

TypeScript is a strongly typed superset of JavaScript that adds static types to the language, making it easier to write more robust and maintainable code. It compiles down to plain JavaScript and works seamlessly with existing JavaScript projects. Here’s a quick guide on getting started with TypeScript.
1. Install Node.js and TypeScript
Before diving into TypeScript, you need to have Node.js installed on your machine. Node.js comes with the Node Package Manager (NPM), which is used to install TypeScript.
Install Node.js: Visit Node.js official website and follow the installation instructions for your operating system.
Install TypeScript: Once you have Node.js installed, open your terminal and install TypeScript globally by running:
npm install -g typescript
To verify that TypeScript is installed correctly, check the version:
tsc --version
2. Set Up a TypeScript Project
Now, create a new directory for your project and initialize a new NPM project:
mkdir my-typescript-app
cd my-typescript-app
npm init -y
This creates a package.json
file, which will manage your project’s dependencies.
3. Install TypeScript Locally in Your Project
You can also install TypeScript locally to your project (though it's already installed globally):
npm install typescript --save-dev
Once installed, create a tsconfig.json
file. This file is used to configure the TypeScript compiler (tsc
):
npx tsc --init
The tsconfig.json
file contains default settings, but you can customize it based on your project’s requirements.
4. Write Your First TypeScript File
Create a new file called app.ts
. This file will contain TypeScript code:
function greeter(person: string) {
return "Hello, " + person;
}
let user = "Coder Playground";
console.log(greeter(user));
In this code:
- Type Annotations: The
greeter
function expects a parameterperson
of typestring
. - Type Inference: TypeScript can infer the type of the
user
variable from the assigned value.
5. Compile TypeScript to JavaScript
To compile the TypeScript code into JavaScript, run the TypeScript compiler:
npx tsc app.ts
This generates a new file, app.js
, with the compiled JavaScript:
function greeter(person) {
return "Hello, " + person;
}
let user = "Coder Playground";
console.log(greeter(user));
You can now run the JavaScript file using Node.js:
node app.js
6. Working with Types
One of the main advantages of TypeScript is its type system. It helps catch errors early during development, making your code more robust.
Here are a few ways to use types in TypeScript:
Basic Types: You can annotate variables, function parameters, and return types.
let isDone: boolean = false;
let count: number = 42;
let userName: string = "Coder";
let list: number[] = [1, 2, 3];
Interfaces: Interfaces allow you to define the shape of an object.
interface User {
name: string;
age: number;
}
function printUserInfo(user: User) {
console.log(`Name: ${user.name}, Age: ${user.age}`);
}
const newUser = { name: "Alice", age: 30 };
printUserInfo(newUser);
Union Types: A variable can hold values of multiple types using union types.
let id: number | string;
id = 10; // valid
id = "10"; // also valid
Optional Properties: You can specify optional properties in interfaces using ?
.
interface Product {
name: string;
price: number;
description?: string;
}
const product: Product = {
name: "Laptop",
price: 1000
};
7. TypeScript with Classes
TypeScript also supports object-oriented programming with classes, inheritance, and access modifiers (public
, private
, and protected
):
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
public makeSound() {
console.log(`${this.name} makes a sound`);
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
public makeSound() {
console.log(`${this.name} barks`);
}
}
const dog = new Dog("Buddy");
dog.makeSound(); // Buddy barks
8. TypeScript Tooling
To enhance your development experience, consider using tools that integrate well with TypeScript:
Visual Studio Code: VS Code has built-in support for TypeScript. It provides features like IntelliSense, error highlighting, and quick fixes.
TypeScript Watch Mode: You can automatically recompile your TypeScript code whenever changes are made by using watch mode:
npx tsc --watch
ESLint: For linting TypeScript code, you can integrate ESLint with TypeScript to enforce code style and standards.
9. Working with Modules
TypeScript supports modules, which allow you to organize your code into separate files:
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
// app.ts
import { add } from './math';
console.log(add(10, 20)); // 30
To compile a project with multiple files, use npx tsc
without specifying a file name, and TypeScript will compile all the files referenced in the project.
10. Running TypeScript with Node.js Using ts-node
Instead of compiling TypeScript into JavaScript every time, you can use ts-node
, which allows you to run TypeScript directly:
npm install -g ts-node
ts-node app.ts
npm install -g ts-node
ts-node app.ts
Conclusion
TypeScript brings strong typing, modern JavaScript features, and tooling to your development workflow, making it a great choice for building scalable and maintainable applications. Whether you’re working on small projects or large enterprise-level applications, TypeScript can help you catch errors early and write more predictable code.
Let me know if you’d like to dive deeper into any TypeScript concepts!