Typescript for Beginners I: Introduction
TypeScript is a programming language that builds on top of JavaScript, adding optional static typing, classes, and other features that help developers write better code. In this chapter, we’ll introduce some of the basic syntax and concepts of TypeScript and show how it differs from plain JavaScript.
Installing TypeScript
Before we start writing TypeScript code, we need to install the TypeScript compiler. You can install it using npm (Node Package Manager), which is included with Node.js. Open a terminal window and run the following command:
npm install -g typescript
This will install the latest version of TypeScript globally on your system.
Basic Types
One of the main features of TypeScript is static typing. This means that we can declare the types of variables, parameters, and return values, which helps catch errors early and makes the code more self-documenting. Here are some of the basic types in TypeScript:
let name: string = "Alice";
let age: number = 30;
let isStudent: boolean = true;
let hobbies: string[] = ["reading", "swimming", "traveling"];
let person: { name: string, age: number } = { name: "Bob", age: 25 };
In this example, we declare a variable name
of type string
, a variable age
of type number
, a variable isStudent
of type boolean
, an array hobbies
of type string[]
, and an object person
with properties name
and age
of the respective types. Note that we use the colon (:
) to indicate the type after the variable name.
Functions
Functions in TypeScript can also have typed parameters and return values. Here’s an example:
function greet(name: string): void {
console.log(`Hello, ${name}!`);
}
greet("Alice");
In this example, we declare a function greet
that takes a parameter name
of type string
and returns void
(i.e., nothing). Inside the function, we use template literals (backticks) to create a string that includes the value of the name
parameter. Finally, we call the function with the argument "Alice"
.
Classes
TypeScript also introduces the concept of classes, which are similar to classes in object-oriented languages like Java or C#. Here’s an example:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
let person = new Person("Alice", 30);
person.greet();
In this example, we define a class Person
with properties name
and age
, and a constructor that takes two parameters and assigns them to the respective properties. We also define a method greet
that logs a message to the console. Finally, we create a new instance of the Person
class and call the greet
method.
Conclusion
In this chapter, we’ve introduced some of the basic concepts and syntax of TypeScript, including static typing, basic types, functions, and classes. In the next chapter, we’ll dive deeper into the language and explore some of its more advanced features.