/typescript-learning

Typescript tutorials, self-taught learning, ...

Primary LanguageHTML

1. TypeScript Learning

TypeScript tutorials, self-taught learning, ...

TypeScript Course for Beginners 2021: https://www.youtube.com/watch?v=BwuLxPH8IDs

1.1. How to run examples

tl;dr

# In a first shell
npm install   # install the dependencies
npm start     # start the local server with live reload (open a new browser tab)

# In another shell
# Found the example you want to try and copy/paste its content into app.ts
npm run compile:watch

# The browser shows the result (you may need to open your dev console (F12))!

1.2. What is TypeScript

  • Youtube timecode: https://youtu.be/BwuLxPH8IDs?t=118
  • TypeScript = JavaScript superset
  • TypeScript is compiled to JavaScript
  • In JavaScript, developers can still write invalid code (simple example: '2' + '3' = '23' instead of '5')
  • TypeScript is a tool that helps developers write better code (but only helps during development, i.e. before the code gets compiled)
  • JavaScript uses "dynamic types", TypeScript uses "static types"
  • TypeScript helps during development while JavaScript checks should help during runtime

1.3. Installing and using TypeScript

npm install -g typescript
  • Compile *.ts files with the command
cd examples/2-typescript-basics
tsc using-ts.ts
  • Convert a string parameter num1 to a number one as +num1 (not in method signature)
  • TypeScript add
    • types
    • next-gen JavaScript features (compiled down for older platforms/browsers)
    • non-JavaScript features like Interfaces or Generic
    • meta-programming features like decorators
    • ruch configuration options
    • modern tooling that helps even in non-TypeScript projects

1.4. IDE

  • Visual Studio Code: https://code.visualstudio.com/download
  • Extensions:
    • Eslint: dbaeumer.vscode-eslint
    • Path intellisense: christian-kohler.path-intellisense
    • Prettier: esbenp.prettier-vscode

1.5. Lite-server

Allow live reload of the .js files

npm install --save-dev lite-sever

Add a new "start" npm script

{
  "scripts": {
    "start": "lite-server"
  }
}

Run the Lite server

npm start

Now, you just have to compile the .ts files to see the result into your browser without refreshing the page

1.6. Types

1.6.1. Core types

  • number: integers, floats, negative integers (1, 5.3, -10)
  • string: text values ('Hi', "Hi", Hi)
  • boolean: true or false, no "truthy"/"falsy" values like 0
  • object: {age: 30}, any JavaScript object, more specific types (type of object) are possible
  • Array: [1, 2, 3], any JavaScript array, type can be flexible or strict (regarding the element types)
  • Tuple: [1, 2], JavaScript array with fixed-length and fixed-type
    • When you know the exact length of an array and the exact datatype in advance then you might want to consider a tuple of an array to get even more strictness into your app
  • Enum: enum {NEW, OLD}, automatically enumerated global constant identifiers (can be [upper/lower]case)
  • Any: *, any kind of value, no specific type assignment (avoid Any whenever possible)
    • The compiler can't check anything, the Any datatype takes away all advantages TypeScript gives you

1.6.2. Type inference

TypeScript does not need to get the type of a const when setting it, the "TypeScript type inference" feature will understand which type is a certain variable, constant.

const number1 = 5; // 5 is a number so number1 is a number constant
const myStr = "hello world"; // 'hello-world' is a string so myStr is a string constant
const isReady = true; // true is a boolean so isReady is a boolean constant

Datatype shoudn't be added if the value is set but it could if we don't initialize it immediatly

// Correct
let number1;

// Better
let number1: number;

// Wrong: break the infered type: Type "'5'" is not assignable to "number"
let number2: number;
number2 = "5";

1.7. Troubleshooting datatypes

  • Duplicate function implementation ts(2393) warning from the IDE: the filename.ts and filename.js are both open, close the filename.js file tab
  • Type "'5'" is not assignable to "number" error means we're breaking the infered type of a constant/variable

1.8. Configuring the Typescript compiler

1.8.1. Watch

To prevent running manually the compiler after each file change, use the --watch flag

tsc app.ts --watch

1.8.2. Several files to watch/compile

If you have several files to watch and compile, init a Typescript config file

tsc --init

1.8.3. Sourcemaps

Sourcemaps allow to "map" the *.ts files to their *.js dist file. It improves debugging on important project by allowing to debug *.ts files directly into the dev console's debugger.

In the tsconfig.json file, enable the "sourceMap" option

{
  "compilerOptions": {
    // ...
    "sourceMap": true /* Create source map files for emitted JavaScript files. */
    // ...
  }
}