Getting Started with TypeScript: The Basics Explained
Mike Codeur
TypeScript is an extension of JavaScript that adds static typing to your code. This helps catch errors at compile time, making your code more robust and maintainable. In this article, we will explore the basics of TypeScript with clear and concise examples to help you get started.
Why Use TypeScript?
Before diving into the code, here are some key advantages of TypeScript:
- Static Typing: It helps catch errors before execution.
- Autocomplete and Documentation: Tools like VS Code provide enhanced autocomplete and documentation thanks to TypeScript.
- Interoperability: TypeScript works seamlessly with existing JavaScript projects.
- Maintainable Code: Types facilitate team collaboration and the management of complex projects.
Installing TypeScript
To start with TypeScript, install it globally via npm:
npm install -g typescript
To verify that TypeScript is installed:
tsc --version
Your First TypeScript File
Create a file named app.ts
:
function greet(name: string): string {
return `Hello, ${name}!`;
}
const message = greet("Alice");
console.log(message);
Compile this file with the following command:
tsc app.ts
This will generate a app.js
file that you can execute with Node.js.
Basic Types
1. string
Type
const firstName: string = "John";
2. number
Type
const age: number = 25;
3. boolean
Type
const isDeveloper: boolean = true;
4. Arrays
const skills: string[] = ["TypeScript", "JavaScript", "React"];
5. Objects
const user: { name: string; age: number } = {
name: "Alice",
age: 30,
};
6. any
Type
The any
type disables type checking. However, its use should be avoided whenever possible.
let randomValue: any = "Hello";
randomValue = 42; // No issues here.
Functions in TypeScript
TypeScript allows you to define types for function parameters and return values.
function add(a: number, b: number): number {
return a + b;
}
const sum = add(10, 20);
console.log(sum);
Parameters can also be optional:
function greetUser(name: string, age?: number): string {
return age ? `Hello, ${name}. You are ${age} years old.` : `Hello, ${name}.`;
}
console.log(greetUser("Alice"));
console.log(greetUser("Bob", 25));
Interfaces and Types
Interfaces define structures for objects.
interface User {
name: string;
age: number;
isAdmin: boolean;
}
const newUser: User = {
name: "Charlie",
age: 28,
isAdmin: false,
};
Types can also be used to create aliases:
type Point = {
x: number;
y: number;
};
const origin: Point = { x: 0, y: 0 };
Enums
enums
are used to define a set of constant values.
enum Direction {
Up,
Down,
Left,
Right,
}
const move = Direction.Up;
console.log(move); // Outputs 0 (index of the value)
Classes
TypeScript supports object-oriented programming with classes and interfaces.
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
const person = new Person("Alice", 30);
console.log(person.greet());
Configuring tsconfig.json
To configure your TypeScript project, initialize a tsconfig.json
file:
tsc --init
A typical configuration file may look like this:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true
}
}
Conclusion
TypeScript is a powerful tool for writing safer and more maintainable JavaScript code. By understanding the basics such as types, interfaces, and classes, you will be well-equipped to build robust applications.
Feel free to explore further and apply TypeScript to your existing projects to fully experience its benefits.