I wrote this code and notes during the Understanding Typescript course from Udemy made by Maximilian Schwarzmüller
Typescript is a JavaScript superset adding new features.
TS -> compiled to -> JS
- Avoid unwanted behavior at runtime.
- Catch errors during development.
Fail during development and not on runtime
This example uses two number inputs that always return a number, but we must check the input first to avoid problems.
function add(n1, n2) {
if (typeof n1 !== 'number' || typeof n2 !== 'number') {
throw new Error('Incorrect input!');
}
return n1 + n2;
}
TypeScript forces us to be more explicit and clear about our intentions and double-check our code.
function add(n1: number, n2: number) {
return n1 + n2;
}
- Types
- Next-Gen JS features
- Meta-Programming features like decorators
- Rich configurations options
- Modern tooling that helps even in non-TypeScript projects
VS code extensions: Path Intellisens, ESLint, TSLint, Prettier,
npm init
npm install --save-dev lite-server
Open package.json
file and add a script named "start" with the value lite-server
, like this:
"scripts": {
"start": "lite-server"
},
To run the project use the command:
npm start
The lite-server
will update the page after the TS is compiled.
let number1: number;
number = 10;
We need to add typing only on uninitialized variables.
All type casing on TS is always lowercase.
- Number: 1, 53, -10
- String: 'Hi', "Hi", `Hi`
- Boolean: true, false (0 = falsy, 1 = truthy)
A constant is different from a variable.
This is how we create objects in JavaScript:
{
name: 'Diego';
}
Now, using TypeScript:
const person = { name: string; } = { name: 'Diego' }
Add type assignments like this is not a good practice!
Types and types assignments are not JavaScript
hobbies: string[] = ['Sports', 'Cooking'];
An array could be flexible or strict.
- Array of Strings -> string[]
- Array of any type -> any[]
Tuple is an array with fixed length and types.
role: [2, 'author'];
Push works with tuples.
enum Role {
ADMIN, // index: 0
READ_ONLY // index: 1
AUTHOR // index: 2
}
Two different types of value
number | string;
We may need a runtime check to avoid errors when using union types.
resultConversion: 'as-number' | 'as-test';
type name = number | string;
type name = 'as-number' | 'as-text';
tsc <filename> --watch or -w
tsc init
This command generates a tsconfig.json
file where we can change the project configurations.
Import file into each other is called "modules".
"exclude": ["**/*.dev.ts", "node_modules"],
"include": ["./src/*"]
- Exclude -> Remove all listed files and/or matches
- Include -> The opposite of exclude
- target: JS output version
- lib: API needed to interact with, for example: "DOM"
- sourceMap: Connects JS file to a TS file on DevTools
- outDir: Where to store the compiled files.
- downlevelIteration: If the loops don't work as expected
- noEmitOnError: When set to true does not generate a JS file if the code has an error
- strict: Use all strictOptions when set to true
Add chrome debug extension to VS code.
OOP stands for Object-Oriented Programming
Use real-life entities in your code.
Objects -> The things you work with in code.
Classes -> Blueprints for an object.
Instances -> An object created with a class.
class Department {
name: string;
constructor(n: string) {
this.name - n;
}
}
The
this.
will refer to the thing that called it.
By doing a validation on a method we avoid using this method with objects that are not Department
, so they may not have the necessary properties. The parameter this: Department
helps typescript catch unwanted behaviors.
class Department {
...
describe(this: Department) {
...
}
}
class Department {
name: string;
private employees: string[] = [];
constructor(n: string) {
this.name - n;
}
}
Accessing this property directly should not be allowed, that why it is private. This code will return and error:
const accounting = new Department('Accounting');
accounting.employees[2] = 'Anna'; // Trying to modify a private property
class Department {
constructor(private name: string) {
...
}
}
The readonly
property blocks this property from being changed.
class Department {
constructor(private readonly name: string) {
...
}
}