TypeScript has caused endless debates among developers. Some see it as a bureaucratic roadblock to the freedom of JavaScript, while others hail it as a beacon of light in the trenches of loosely typed code. Love it or hate it, TypeScript is here to stay — and once you get to know it, you might just find it’s not a burden but a blessing for your projects.
In this series we will explore TypeScript and cover the basics -- as well as some tricks and troubleshooting tips.
1. Introduction
What is TypeScript?
TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. In simpler terms, it’s JavaScript with extra features that help you catch errors early and write better, more maintainable code.
Think of TypeScript as a friendly assistant who double-checks your work before you submit it. It lets you:
- Spot errors while you’re coding, not after you’ve deployed.
- Write code that’s easier to read and understand.
- Scale your projects without losing track of how things connect.
Why Use TypeScript?
Let’s get practical. Why should you care about TypeScript when JavaScript already works?
Real Benefits:
- Catch Errors Early: Avoid common pitfalls, like passing the wrong data type to a function.
function greet(name: string) {
return `Hello, ${name}!`;
}
greet(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
Autocompletion & Documentation: Modern editors (like VS Code) provide rich autocomplete suggestions and documentation as you type.
Code Scalability: TypeScript’s features shine in larger projects where maintaining consistency is key.
Improved Team Collaboration: Clear types make it easier for team members to understand your code at a glance.
I have found TypeScript to be particularly helpful for planning out bigger apps; understanding what types of data I will be dealing with and what data my functions take/return.
Prerequisites
Before diving in, ensure you have basic JavaScript knowledge. You should be familiar with:
- Variables and data types (e.g.,
let
,const
,string
,number
) - Functions
- Arrays and objects
If you’re not confident yet, take some time to review JavaScript basics.
2. Setting Up Your Environment
Installing TypeScript
TypeScript is a tool that requires installation to get started. With just a few steps, you can prepare your environment to begin coding in TypeScript. Here’s how to do it:
To start using TypeScript, you’ll need Node.js installed. Once you have that:
- Install TypeScript globally:
npm install -g typescript
- Verify the installation:
tsc --version
Setting Up VS Code
VS Code is one of the most popular editors for TypeScript development. It provides a range of features and extensions that make coding easier and more efficient. Let’s set it up:
VS Code is the go-to editor for TypeScript developers. Here’s how to set it up:
- Install VS Code: Download here
- Add these helpful extensions:
- ESLint: For linting your TypeScript code.
- Prettier: For consistent code formatting.
- TypeScript Hero: For improved productivity.
Creating Your First TypeScript Project
Getting hands-on is the best way to learn TypeScript. This section guides you through setting up your first project, from creating files to running your code.
- Create a new folder for your project and navigate into it:
mkdir typescript-starter
cd typescript-starter
- Initialize a new project:
npm init -y
- Add TypeScript:
npm install --save-dev typescript
- Create a
tsconfig.json
file:
npx tsc --init
- Write your first TypeScript file:
echo "console.log('Hello, TypeScript!');" > index.ts
- Compile and run:
npx tsc index.ts
node index.js
You’ve just written and compiled your first TypeScript program!
3. Basic Types Overview
TypeScript’s power lies in its type system. Let’s explore some basic types:
Primitive Types
Primitive types are the building blocks of TypeScript’s type system. They include basic data types like strings, numbers, and booleans. Here’s a quick look at how to use them:
-
string
:
let name: string = "Alice";
-
number
:
let age: number = 25;
-
boolean
:
let isStudent: boolean = true;
Advanced Types
In addition to primitives, TypeScript supports more complex types like arrays, tuples, and special types like any
and unknown
. These types make your code flexible while maintaining safety.
- Arrays:
let scores: number[] = [90, 85, 88];
- Tuples:
let user: [string, number] = ["Alice", 25];
-
any
(use sparingly):
let data: any = "Could be anything";
-
unknown
(safer thanany
):
let value: unknown = 10;
-
void
(functions that return nothing):
function logMessage(message: string): void {
console.log(message);
}
-
null
andundefined
:
let something: null = null;
let nothing: undefined = undefined;
4. First Steps with Type Annotations
Type Annotations in TypeScript allow developers to specify the type of a variable, parameter, or function return value. This ensures that the code adheres to a defined structure, making it easier to catch errors during development and maintain consistency throughout the project.
As you write your code as you normally do, take note of the features below that you can integrate
Basic Variable Typing
Set types for your variables so that they are always set to the right thing, and the rest of the app understands what they are.
let firstName: string = "Alice";
let age: number = 30;
Function Parameter Typing
Similarly, for functions you can define the types for the arguments, as well define the type for the return.
// Note the 'number' keywords for each param
function add(a: number, b: number): number {
return a + b;
}
Return Type Annotations
// Note the 'string' keyword at the end
function greet(name: string): string {
return `Hello, ${name}!`;
}
Practical Example: User Profile
TypeScript allows you to declare your own types to better structure and enforce rules in your code. By using type
or interface
, you can define custom types for objects, functions, or even unions. This not only makes your code more robust but also improves readability and consistency in larger projects.
interface UserProfile = {
name: string;
age: number;
isActive: boolean;
};
const user: UserProfile = {
name: "Alice",
age: 25,
isActive: true,
};
5. Quick Start with Interfaces
Basic Syntax
Interfaces in TypeScript define the structure of objects, ensuring they have specific properties and types. This section shows you how to create and use them:
interface User {
name: string;
age: number;
}
const user: User = {
name: "Bob",
age: 30,
};
Optional Properties
Sometimes, not all properties in an object are required. TypeScript lets you define optional properties in interfaces to handle such cases gracefully.
interface Product {
name: string;
price?: number;
}
const item: Product = { name: "Notebook" };
Readonly Properties
Readonly properties are useful when you want to ensure certain values cannot be changed after they are set. Here’s how to use them in interfaces:
interface Book {
readonly title: string;
}
const myBook: Book = { title: "TypeScript Handbook" };
// myBook.title = "Another Title"; // Error: Cannot assign to 'title'.
Real-World Example: API Response
Using interfaces to type API responses ensures you handle data from servers safely and effectively. Here’s a practical example:
interface ApiResponse {
data: unknown;
status: number;
}
6. Practice Project: Building a Simple Todo List
Practice is key to mastering TypeScript. In this project, you’ll create a simple todo list application that leverages the features you’ve learned so far:
- Create a
Todo
type:
interface Todo {
id: number;
title: string;
completed: boolean;
}
- Build a simple array of todos:
const todos: Todo[] = [
{ id: 1, title: "Learn TypeScript", completed: false },
];
- Add some functions to add todos and mark todos as complete:
function markAsComplete(todo: Todo): Boolean {
let bUpdated = false
todos.map((td:Todo) => {
if (td.id == todo.id){
bUpdated = true
td.completed = true
}
})
return bUpdated
}
function addToDo(todo:Todo): Boolean{
try {
todos.push(todo)
console.log(`Added "${todo.title}"" to list!`)
return true
} catch {
console.log("Error adding to the todo object!")
return false
}
}
7. Next Steps
That's it for now, hope you enjoyed this tutorial. I will be working on some additional tutorials to dig deeper into useful TypeScript features and use cases.
- Coming Up Next: Deep dive into TypeScript functions and advanced types.
-
Resources:
- TypeScript Documentation
- CodeSandbox for practicing TypeScript online.
- Challenge: Create a TypeScript interface for a blog post and use it to type-check a list of blog posts.
See you next time!
Top comments (0)