Bennicci J. Mastering TypeScript. A step-by-step guide...JavaScript apps 2024
Bennicci J. Mastering TypeScript. A step-by-step guide...JavaScript apps 2024
Contents
PART 1: INTRODUCTION TO
TYPESCRIPT.............................................................................
........... 5
Enter TypeScript
....................................................................................................
................ 6
Conclusion
....................................................................................................
..................... 10
Installing TypeScript
....................................................................................................
......... 12
Conclusion
....................................................................................................
..................... 14
Basic Types
....................................................................................................
..................... 16
Type Inference
....................................................................................................
................. 17
Type Guards
....................................................................................................
.................... 17
Type Annotations
....................................................................................................
............. 18
Exercises
....................................................................................................
........................ 18
Answers
....................................................................................................
......................... 18
Declaring Variables
....................................................................................................
.......... 20
Data Types
....................................................................................................
...................... 20
Operators
....................................................................................................
....................... 21
Best Practices
....................................................................................................
................. 22
Functions in TypeScript
....................................................................................................
.... 23
Function Overloads
....................................................................................................
......... 23
Modules in TypeScript
....................................................................................................
...... 24
CommonJS Modules
....................................................................................................
........ 24
Conclusion
....................................................................................................
..................... 25
Interfaces
....................................................................................................
....................... 26
Enums...........................................................................................
..................................... 27
Exercise.........................................................................................
..................................... 28
Generics........................................................................................
..................................... 31
Union Types
....................................................................................................
.................... 32
Intersections
....................................................................................................
................... 33
[ 2]
Exercises
....................................................................................................
........................ 34
Conclusion
....................................................................................................
..................... 36
Debugging Techniques
....................................................................................................
..... 39
Summary
....................................................................................................
........................ 40
Conclusion
....................................................................................................
..................... 45
Conclusion
....................................................................................................
..................... 49
Conclusion
....................................................................................................
..................... 53
Conclusion
....................................................................................................
..................... 57
Project Overview
....................................................................................................
............. 59
Conclusion
....................................................................................................
..................... 63
Conclusion
....................................................................................................
..................... 66
Conclusion
....................................................................................................
..................... 70
[ 3]
EPILOGUE
.................................................................................................
................................. 71
APPENDICES............................................................................
.................................................. 72
APPENDIX A: ADDITIONAL
RESOURCES..................................................................................
...................... 73
[ 4]
[ 5]
Enter TypeScript
TypeScript also checks your code for type errors before it even runs,
reducing the likelihood of runtime errors. When errors do occur,
TypeScript provides more informative and helpful error messages
that can help you quickly identify and fix issues.
[ 6]
Let's dive in! In the next chapter, we'll explore the benefits of
TypeScript.
[ 7]
function greet(name) {
console.log(Hello, ${name}!);
greet('John');
console.log(Hello, ${name}!);
greet('John');
[ 8]
return a + b;
function add(a, b) {
return a + b;
[ 9]
In this code, we're trying to call the add function with null and 2.
The error message is somewhat cryptic, indicating that it can't
convert null to an object.
return a + b;
}
console.log(add(null, 2)); // Error: Type 'null' is not assignable to
type 'number'.
For instance, you can write a TypeScript class that interacts with a
JavaScript library: class Greeter {
greet() {
console.log(Hello, ${this.name}!);
Conclusion
[
10]
11]
• Node.js installed: You can download and install the latest version
from the official website1 or use a package manager like Homebrew
(for macOS) or apt-get (for Linux).
Installing TypeScript
Once you have Node.js and npm set up, install TypeScript using
npm: npm install -g typescript
1 https://nodejs.org/en/download/
12]
Create a new directory for your project and navigate into it: mkdir
my-typescript-project
cd my-typescript-project
Initialize a new npm project with:
npm init -y
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"sourceMap": true,
"outDir": "build"
[
13]
To ensure your code is linted and follows best practices, install the
official TypeScript linter:
Conclusion
In this chapter, we've covered the essential steps for setting up your
environment for TypeScript development. You now have:
• TypeScript installed.
In the next chapter, we'll dive into the basics of TypeScript syntax
and explore its type system.
14]
15]
Basic Types
TypeScript provides several basic types that you can use to annotate
your variables, function parameters, and return values. Here are
some of the most common ones: Number
A numeric value.
String
A sequence of characters.
Boolean
A true or false value.
Array<T>
An array of type T.
Void
The absence of a value (used to indicate that a function doesn't
return anything).
Null
A special value that represents the intentional absence of any object
value.
Undefined
A special value that represents an uninitialized or non-existent
variable.
// Array types
16]
Type Inference
For example:
let x = 5; // inferred type: number
console.log(Hello, ${name}!);
greet('John'); // no error!
Type Guards
interface Animal {
sound: string;
breed: string;
if (pet.isDog) {
console.log(This is a ${pet.breed}!);
} else {
17]
console.log('Not a dog');
In this example, we define two interfaces Animal and Dog, with the
latter extending the former. We then create a type guard isDog that
checks if an object has a breed property. If it does, we can safely
assume it's a Dog.
Type Annotations
Exercises
3. Write a class Person with properties name and age. Then, create
an instance of Person with explicit types for each property.
Answers
2. Solution:
18]
return x % 2 === 0;
3. Solution:
class Person {
name: string;
age: number;
this.name = name;
this.age = age;
19]
Declaring Variables
In TypeScript, you can declare variables using the let, const, or var
keywords. The main difference between these keywords is the scope
of the variable:
// var variable
Note that in TypeScript, you need to specify the data type of the
variable using a colon followed by the type (e.g., string, number,
etc.).
Data Types
You can also use the any type to indicate that a variable can hold
any type of data.
20]
// boolean variable
Operators
Arithmetic operators
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (remainder)
// arithmetic example
Comparison operators
+ == (equal to)
// comparison example
21]
Logical operators
+ || (logical or)
+ ! (logical not)
// logical example
Assignment operators
+ = (assignment)
+ += (addition assignment)
+ -= (subtraction assignment)
+ *= (multiplication assignment)
+ /= (division assignment)
+ %= (remainder assignment)
// assignment example
x += 5; // equivalent to x = x + 5;
Best Practices
Here are some best practices to keep in mind when working with
variables, data types, and operators:
{ ... }).
[
22]
Functions in TypeScript
return a + b;
Function Overloads
23]
return a + b + c;
// greeter.ts
console.log(Hello, ${name}!);
// main.ts
CommonJS Modules
// greeter.js
function greet(name) {
24]
console.log(Hello, ${name}!);
}
exports.greet = greet;
// main.ts
Conclusion
You saw how to define simple functions with type annotations, use
function overloads to provide multiple entry points, and work with
ES6 and CommonJS modules.
25]
Interfaces
interface Person {
name: string;
age: number;
Now, let's create a class that implements the Person interface: class
Employee implements Person {
name: string;
age: number;
this.name = name;
this.age = age;
26]
Enums
enum Color {
Red,
Green,
Blue,
Here, we've defined a Color enum with three possible values: Red,
Green, and Blue.
Any property or variable that uses this enum must be one of these
exact values.
color: Color;
constructor(color: Color) {
this.color = color;
In this example, we've created a Car class with a color property that
can only be one of the values defined in the Color enum. Any
attempt to assign an invalid value will result in a compiler error.
• You want to create a set of named values for easier coding and
readability.
27]
Now that we've learned about interfaces and enums, let's combine
them to create a more complex example:
interface Vehicle {
color: Color;
wheels: number;
enum Color {
Red,
Green,
Blue,
color: Color;
wheels: number;
this.color = color;
this.wheels = wheels;
28]
29]
Practices
30]
Generics
return value * 2;
console.log(double(42)); // Output: 84
class Container<T> {
private value: T;
constructor(value: T) {
this.value = value;
31]
getValue(): T {
return this.value;
console.log(numContainer.getValue()); // Output: 42
Union Types
Union types allow you to combine multiple types into a single type
that represents all possible values of those types. In other words, a
union type is a way to say, "this value can be one of these things."
if (myValue) {
32]
Union types are useful when you need to represent multiple possible
values for a variable, but you don't want to create separate variables
for each type. For example, you might use union types when
working with user input data that can be either a number or a string.
Intersections
interface Person {
name: string;
salary: number;
When you try to assign another object that is missing one of the
required properties (e.g., myEmployee = { salary: 60000 }),
TypeScript throws an error because the assignment does not match
the intersection type.
33]
Exercises
34]
Here's an example:
interface Person {
name: string;
console.log(Hello, ${person.name}!);
35]
Here's an example:
Now that we've learned about both type guards and conditional
types, let's see how they can be combined to create powerful type
definitions: type IsPerson<T> = T extends { name: string } ? true :
false; function isPerson<T>(obj: T): obj is Person {
return IsPerson(obj);
if (isPerson(person1)) {
console.log(Hello, ${person1.name}!);
Conclusion
36]
37]
Error Codes
In addition to error types, TypeScript also provides error codes that
can be used to provide more context about the error. These codes
are represented as numbers and can be accessed using the .code
property on an error object.
Here's an example:
try {
} catch (error) {
By checking the error code, you can determine the specific reason
for the error and provide more targeted debugging or logging
information.
38]
Debugging Techniques
debugger
return x + y;
console.log(calculate(2, 3));
Here's an example:
return fetch('https://example.com/data')
.catch(error => {
});
}
39]
In this example, we use the catch method to catch any errors that
occur when fetching data. We log the error and re-throw it using
throw error, which allows the error to propagate up the call stack.
Here's an example:
try {
} catch (error) {
Summary
• Error codes
40]
41]
Example:
// Good:
const userInformation = {
};
42]
// Bad:
Structure your code into logical folders and files based on features,
components, or domains. This helps you locate specific code quickly
and makes it easier to share or reuse.
Example:
my-app/
src/
components/
Button.tsx
InputField.tsx
...
views/
Home.tsx
About.tsx
...
utils/
math.js
stringHelper.js
...
index.ts
package.json
Example:
return a + b;
43]
Example:
// Good
// Bad:
Break down large functions into smaller, reusable modules with clear
responsibilities.
Example:
// Good:
}
// Bad:
Example:
44]
// Good:
return userRoles.includes('admin');
// Bad:
Example:
Conclusion
45]
46]
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"jsx": true,
"strict": true,
"esModuleInterop": true
Now that we have our project set up, let's write a simple React
component in TypeScript:
47]
// src/components/Hello.tsx
interface Props {
name: string;
};
"compilerOptions": {
"module": "es2020",
"target": "es6",
"strict": true,
"esModuleInterop": true
48]
Now that we have our project set up, let's write a simple Angular
component in TypeScript:
// src/app/components/hello.component.ts
interface Props {
name: string;
@Component({
selector: 'app-hello',
})
constructor() {
this.name = 'World';
Conclusion
49]
2. Create a new directory for your project and navigate to it: mkdir
my-typescript-app
cd my-typescript-app
50]
4. Create a new file called app.ts and add the following code to it:
import express from 'express';
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
"compilerOptions": {
"outDir": "build",
"sourceMap": true,
"strict": true,
"module": "commonjs",
"target": "es6"
},
"include": ["src/**/*"],
"exclude": ["node_modules/**/*"]
51]
const users = [
];
res.json(users);
});
app.listen(3000, () => {
52]
});
2. Create a new file called user.ts and add the following code to it:
export interface User {
id: number;
name: string;
}
This code defines a simple User interface that represents a user
entity.
Conclusion
In the next chapter, we move to the “front end” to explore the Vue.js
and Nuxt frameworks.
53]
Chapter 14: Using TypeScript with Vue.js and Nuxt As you've learned
more about TypeScript in this book, you're probably eager to put
your new skills to the test by using it with a popular frontend
framework like Vue.js or Nuxt. In this chapter, we'll explore how to
use TypeScript with both Vue.js and Nuxt.
cd my-vue-app
// main.ts
createApp(App).use(router).mount('#app');
<template>
<div>
</div>
</template>
<script lang="ts">
[
54]
export default {
setup() {
},
};
</script>
1. Create a new directory for your project and navigate into it: mkdir
my-nuxt-app
cd my-nuxt-app
target: 'server',
typescript: {
tsConfig: 'tsconfig.json',
},
});
55]
// tsconfig.json
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
<template>
<div>
</div>
</template>
<script lang="ts">
export default {
setup() {
},
};
</script>
When using TypeScript with Vue.js or Nuxt, there are a few things to
keep in mind:
• Make sure you have the correct type definitions installed for your
framework of choice. For example, you'll need to install @types/vue
for Vue.js.
56]
Conclusion
In this chapter, we've seen how to use TypeScript with both Vue.js
and Nuxt. By using type definitions and configuring your TypeScript
compiler correctly, you can take advantage of the benefits of static
typing in your frontend projects. Whether you're building a simple
web app or a complex single-page application, TypeScript is a
valuable tool that can help you write better code and avoid errors.
57]
58]
Chapter 15: Building a Simple To-Do List App In this chapter, we're
going to build a simple to-do list app using TypeScript. This project
will help us apply the concepts learned so far and demonstrate how
to create a functional web application with TypeScript.
Project Overview
We'll be using the React library to build our app, as it's a popular
choice for building user interfaces in TypeScript. If you're new to
React, don't worry – we'll cover the basics as we go along.
Create a new directory for your project and run the following
commands: npm init -y
This will create a new React app with TypeScript set up. Move into
the project directory: cd todo-list
TaskComponent.tsx
59]
interface TaskProps {
task,
onEdit,
onDelete,
}) => {
if (onEdit) {
};
const handleDelete = () => {
if (onDelete) {
onDelete();
};
return (
<div>
<input
type="checkbox"
checked={task.completed}
onChange={() =>
/>
{task.name}
<button onClick={handleEdit}>Edit</button>
<button onClick={handleDelete}>Delete</button>
</div>
);
};
export default TaskComponent;
TaskList.tsx
interface TaskListProps {
60]
return (
<ul>
{tasks.map((task) => (
<li key={task.id}>
</li>
))}
</ul>
);
};
export default TaskList;
App.tsx
interface AppProps {
return (
<div>
<h1>To-Do List</h1>
</div>
);
};
In this section, we'll implement the logic for our to-do list app.
TodoService.ts
[
61]
interface Todo {
id: number;
name: string;
completed: boolean;
];
};
};
};
};
App.tsx (updated)
interface AppProps {
return (
<div>
62]
<h1>To-Do List</h1>
</div>
);
};
Conclusion
In this chapter, we built a simple to-do list app using TypeScript and
React. We covered the basics of building a functional web application
with TypeScript and applied our knowledge of interfaces, classes,
and type inference.
63]
Requirements
Before we start coding, let's outline what our weather forecast app
should do: 1. Allow users to input a city name or zip code
// weather.service.ts
interface WeatherResponse {
city: string;
temperature: number;
condition: string;
interface CityData {
name: string;
zipCode: string;
[
64]
// weather.service.ts
...
class WeatherService {
return this.parseWeatherData(data);
}
}
In this implementation:
• We parse the JSON response using the json() method and extract
the relevant data (temperature and condition).
// weather.component.ts
interface WeatherComponentProps {
city: CityData;
class WeatherComponent {
65]
constructor(service: WeatherService) {
this.service = service;
<h2>${data.city}</h2>
<p>Temperature: ${data.temperature}°C</p>
Here:
Create a new file called main.ts to contain our app entry point:
// main.ts
console.log(component.render());
Conclusion
66]
67]
4. Delete books
Before we start coding, let's set up our project using Node.js and
Express.js.
Now that we have our project set up, let's create the API routes.
[
68]
app.get('/books', getBooks);
app.post('/books', createBook);
app.put('/books/:id', updateBook);
app.delete('/books/:id', deleteBook);
app.listen(port, () => {
});
// API functions
res.json(books);
69]
We're using TypeScript to define our API routes, which provides type
safety and code completion for our API functions. We've also used
the Request and Response types from Express.js to specify the types
of the request and response objects.
Conclusion
70]
Epilogue
We hope that this guide has provided you with a solid foundation in
TypeScript and will serve as a valuable resource for your future
learning and development!
71]
Appendices
72]
https://learn.microsoft.com/en-us/training/modules/typescript-get-
started/
TypeScript Documentation
https://www.typescriptlang.org/docs/
https://www.codecademy.com/learn/learn-typescript
Pluralsight: Typescript
https://www.pluralsight.com/paths/typescript
73]