# TypeScript Tutorial for Beginners
## Get Started
### What is TypeScript
TypeScript is a programming language to address shortcomings of JavaScript.
TS is built on top of JS with some cool features:
– Static typing
– Code completion
– Refactoring
– Shorthand notations
#### 2 Types or programming languages
##### Statically-typed
Such as C++, C#, Java
We know the type of variables at compile time or while code.
Example: we declare an int var that can only hold int values.
“`js
int number = 10;
“`
##### Dynamically-typed
Such as JavaScript, Python, Ruby
Type is dynamic: it’s determined at one time and it can change at runtime.
“`js
let number = 10;
number = “a”;
“`
Problem: we do not know the issue of pass in a wrong type var until we run our application our unit tests; we have to test every functions with various edge cases to catch these bugs.
#### So TypeScript is
TypeScript is JavaScript with Type Checking.
With TS, we explicitly set the type of our variable upon declaration just like static typed languages.
When we pass our code to our compile, it tells us if we are doing something wrong.
In this way, we catch a lot of our mistakes at compile time.
“`js
let x: number = 10;
x = “a”; // This type error is caught at compile time.
“`
### Drawbacks of TypeScript
Drawbacks
– Compilation
– Discipline in Coding
**Compilation step is always involved**
Browsers don’t understand TS code, so we have to give the code to the TS compiler that compile and translate it to JavaScript. This process is called transpilation.
**Tradeoffs**
TS is good for medium to large projects.
JS is good for getting simple projects done quickly.
## Practical Tutorial
### Setting up the Development Environment
The first thing we need is Node.js, a JavaScript runtime built on Chrome’s V8 JavaScript engine.
We can use node package manager (npm) to install the TS compiler.
To install TS:
– i: install
– g: globally
“`bash
npm i -g typescript
“`
Next, install VS Code if it’s not there yet.
### Your First TS Program
#### Create a ts file and compile
Make a new folder for your TS program and open it in vs code.
“`bash
mkdir hello-world
cd hello-world
code .
“`
Create a new file `index.ts`
Write a simple printing as follows:
“`ts
console.log(“Hello, World!”);
“`
Open a terminal in vs code and compile `index.ts`
“`bash
tsc index.ts
“`
Now, in the same folder, you can see the result of compilation in a new generated file `index.js`.
#### Code with TS features
A number type:
“`ts
let age: number = 20;
“`
After compilation, the js version:
“`js
var age = 20;
“`
We can see the type annotation is gone in the js code.
### Create a Config File for TS Compiler
Create a new config file (`tsconfig.json`) by running:
“`bash
tsc –init
“`
#### Configurations
1 The version of JS that this compiler generates:
“`json
“target”: “esnext”,
“`
2 Directory that contains our source (ts) files:
“`json
“rootDir”: “./src”,
“`
3 Directory that contains our js files:
“`json
“outDir”: “./dist”,
“`
4 How our ts code maps to the generated js code:
“`json
“sourceMap”: true,
“`
#### Change configurations and compile again
Uncomment the rootDir and outDir optoins, create a new folder `src` and move `index.ts` into it. Finally run `tsc` in the terminal to complie it.
### Debug TS Applications in VS Code
Click the debug button on the left panel of vs code, choose `create a launch.json file`. It is a config file that tells vs code how to debug this application.
Add a new config in this file:
“`json
“preLaunchTask”: “tsc: build – tsconfig.json”,
“`
It tells vs code to build the application using this config file.
Now, add a breakpoint in your ts code and click `Launch Program` to start debugging.
You can click `step over` to run the first line. You see the variables on the left panel and you can add a var to `watch`.
Basically, you do a `step over` and check the variable in Watch.
This is very useful that when our program goes wrong, we can execute our program line by line.
## Fundamentals
### Built-in Types
JavaScript Built-in Types
– number
– string
– boolean
– null
– undefined
– object
TypeScript Built-in Types
– any
– unknown
– never
– enum
– tuple
### The any Type
TypeScript compiler will assume the following variable as any.
If you use any type, you lose the feature of type checking.
For best practice, you should avoid using any type as much as possible.
“`ts
let level;
level = 1;
level = ‘a’;
“`
### Arrays
Example of array as follows:
“`ts
let numbers: numbers[] = [1, 2, 3];
“`
Compiler knows n is a number and offers number methods.
“`ts
numbers.forEach(n => n.valueOf())
“`
### Tuples
Tuple is a fixed length array where each element has a particular type.
We often use them when working with a pair of values.
“`ts
let user: [number, string] = [1, ‘Jack’];
“`
As best practice, restrict your tuples to only two values because anything more than may make your code hard to understand.
### Enums
You can group constant inside an enum, for exmaple:
“`ts
enum Size { Small = 1, Medium = 2, Large = 3 };
let mySize: Size = Size.Medium;
console.log(mySize);
“`
Using Enum, you can represent a list of related constants and if we define Enum with const keyword, the compiler will generate more optimized code.
“`ts
const enum Size { Small = 1, Medium = 2, Large = 3 };
“`
### Functions
An example function as follows:
“`ts
function calculate(income: number): number {
return income * 2;
}
“`
### Objects
An example of object as follows:
“`ts
let employee: {
readonly id: number,
name?: string,
retire: (date: Date) => void
} = {
id: 1,
name = ‘Lucy’,
retire: (date: Date) = {
console.log(date);
}
};
“`
## Advanced Types
### Type Aliases
Using type alias, you can define a custom type, for example:
“`ts
type Employee = {
readonly id: number,
name?: string,
retire: (date: Date) => void
}
let employee: Employee = {
id: 1,
name = ‘Lucy’,
retire: (date: Date) = {
console.log(date);
}
};
“`
### Union Types
With Union type, you can give a variable or function more than one type.
“`ts
function kgToLbs(weight: number | string): number {
if (typeof weight === ‘number’)
return weight * 2.2;
else
return parseInt(weight) * 2.2;
}
“`
### Intersection Types
Using an intersection type we can combine two types.
“`ts
type Draggable = {
drag: () => void
};
type Resizable = {
resize: () => void
};
type UIWidget = Draggable & Resizable;
let textBox: UIWidget = {
drag: () = {},
resize: () = {}
}
“`
### Literal Types
We use literal type to limit the values we can assign to a variable.
“`ts
// Literal (exact, specific)
type Quantity = 50 | 100
let quantity: Quantity = 100;
type Metric = ‘cm’ | ‘inch’;
“`
### Nullable Types
“`ts
fucntion greet(name: string | null | undefined) {
if (name)
console.log(name.toUpperCase());
else
console.log(‘Hola!);
}
greet(null);
“`
### Optional Chaining
“`ts
type Customer = {
birthday: Date
};
function getCustomer(id: number): Customer | null | undefined {
return id === 0 ? null : { birthday: new Date() };
}
let customer = getCustomer(0);
if (customer !== null && customer !== undefined)
console.log(customer.birthday);
// Or using optional property access operator
console.log(customer?.birthday);
“`
## Reference
Youtube video: