TypeScript from Scratch
Hello! Welcome
Today we are going to explore TypeScript from scratch.
What is TypeScript?
TypeScript is a superset of JavaScript that adds static typing and other advanced features to JavaScript.
Static typing allows you to define the type of data (such as numbers, strings, etc.) that a variable can contain. This helps prevent errors before the code is executed.
How does TypeScript work?
TypeScript code is written in files with the .ts
extension. Before you can run it, it is compiled to JavaScript.
This allows you to use TypeScript in any web project that would normally use JavaScript.
Installing TypeScript
To use TypeScript, you need to install it with NPM (Node Package Manager).
- Run the command
npm install -g typescript
to install it globally.
You will also need a development IDE, such as Visual Studio Code.
You’re doing great!
Now let’s talk about types in TypeScript.
Types in TypeScript
TypeScript allows you to use basic types for variables and functions, such as string
, number
, boolean
, and more.
For example:
let name: string = "Luis";
let age: number = 25;
But you can also create custom types, for example using type
.
Arrays and Tuples
We can also define arrays and tuples:
- Array: Declared with
type[]
orArray<type>
. - Tuple: Defines a collection of fixed length and specific types.
let numbers: number[] = [1, 2, 3]; // array
let pair: [string, number] = ["age", 30]; // Tuple
Union Types and Literal Types
Literal and union types use the |
operator to combine values or types.
- Literal: Specifies allowed fixed values.
- Union: Allows a variable to accept multiple types.
let direction: "north" | "south" | "east" | "west"; // literal
let result: number | string = 42; // union
Classes and Interfaces
TypeScript also adds many features of object-oriented programming.
For example, you can define classes, with methods, attributes, encapsulation, and inheritance.
You can also use interfaces that specify what properties and methods must be present.
You’re almost there!
Now we just need to see how to program your Arduino.
Getting Started with TypeScript
Create a file with the .ts
extension, like app.ts
. Inside it, write this code:
let message: string = "Hello, LuisLlamas.es!";
console.log(message);
Write TypeScript code in this file, and then compile it to JavaScript using the command tsc app.ts
.
Compiling TypeScript
Use the tsc
command to compile TypeScript files to JavaScript.
Compile it to JavaScript using the command tsc app.ts
.
This will generate a hello.js
file with the same code in JavaScript.
Running the Code
Finally, run the compiled file using Node.js:
node hello.js
Congratulations! You just created your first program in TypeScript. Ready to keep progressing!
Well Done!
Now you have the basics of TypeScript! Keep practicing and exploring.