Learning Typescript in 324 Pages -pages (1- 36)

Learning Typescript in 324 Pages -pages (1- 36)

Part A

Note: This would be a series as i can't possibly finish the book in a day 🙃.

You are probably reading this article because of two reasons:

  1. You are willing to join me on this journey of learning typescript.
  2. You are here to support me.

Either ways it all cool and appreciated ☺️. Without wasting much of time, lets talk about Typescript.

What is Typescript ?

Typescript is essentially a superset of JavaScript and allows us to write type safe, scalable code as developers.

Why Typescript ?

One of the major reasons to use typescript is for its type safety i.e., It adds the static type checking that exists in other languages like Golang, Java etc., to JavaScript which is a dynamically typed language.

Type safety means using defined types to prevent programs from doing invalid things.

Examples of invalid operations that JavaScript tries to handle for us but doesn't give the best of help

Multiply an array by a number
[2] * 3 // JavaScript returns 6

function a(b) {
    return b/3
}
a("z") // JavaScript returns NaN

Depending on what you are actually doing in terms of your business logic that could potentially lead to serious bugs as you don't easily catch those errors because JavaScript is trying to handle it to the best of its knowledge without throwing an exception.

Now it may seem nice that JavaScript doesn't instantly throw us an error but then it creates a disconnect between when we make an error and when we find out about the error.

When we get error in JavaScript

We only get our JavaScript type errors when our program is run. Our program might get run when you test it in a browser, or when a user visits your website, or when you run a unit test.

Now this can be fine by you but what if we could get our errors earlier before our code is actually ran 🤔. This is where TypeScript kicks in.

Lets see how typescript handles our example

[2] * 3 // typescript error -> The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts(2362)

function a(b:number) {
    return b/3
}
a("z") // typescript error -> Argument of type 'string' is not assignable to parameter of type 'number'.ts(2345)

With those kind of error messages as above we are able to catch the possible type related bugs in our system before runtime.

How Typescript compiles

Programs are files that contain a bunch of text written by you, the programmer. That text is parsed by a special program called a compiler, which transforms it into an abstract syntax tree (AST), a data structure that ignores things like whitespace, comments. The compiler then converts that AST to a low level representation called bytecode. You can feed that bytecode into another program called a runtime to evaluate it and get a result. So when you run a program, what you’re really doing is telling the runtime to evaluate the bytecode generated by the compiler from the AST parsed from your source code.

  • Code is parsed as AST.
  • AST is converted/complied to bytecode.
  • Bytecode is evaluated at runtime.

How the typescript compiler works:

  • Parses .ts source code as AST to remove spaces and comments.
  • Type Checks the generated AST (here is the beef of typescript).
  • AST is then complied to a JavaScript source file.
  • JavaScript source file is converted to AST.
  • AST is converted to bytecode.
  • Bytecode is then evaluated at runtime.

The first three steps are done by tsc.

Typescript Type System

Type system are set of rules that a type checker uses to assign types to your program.

In some statically typed languages like Golang, there are two ways of defining types i.e ,

  1. Explicit type declaration.
  2. Inferred type declaration. and the same is true for typescript.

To explicitly declare types in typescript you use annotations. Annotations take the form value: type and tell the type checker, to assign the specified type to that value.

let a:number = 3 // a is of type number
let c: Array<boolean> = [true, false] // c is an array containing boolean values

For basic types as the ones above, you are better of allowing typescript infer the types and you should allow typescript infer types as much as possible.

Example of inferred types

let a = 3;
let c = [true, false];

If we hover over each of the declared variables a and c, we see let a:number and let c: boolean[]

Requirements

Now that we've learnt the basics, there are a few things we need to make this process seamless:

  1. IDE.
  2. Node because we need it to run tsc (a command line utitlity).

Run the following to start a boiler plate folder

npm init // initialize a new npm project
npm install typescript tslint @types/node -D // insatll dependencies

touch tsconfig.json // typescript config file

Let's fill in the basic configurations in our tsconfig.json file

{
    "complierOptions":{
          "outDir": "./dist", // output directory to store complied ts file to js
           "module": "commonjs", // module system our ts files should be converted tp
           "lib": ["es6"],
           "target": "es6", // javascript version our ts files should be converted to
           "strict" true
     },
    "include": ["src/"]  // location of our source code
}

Part B would be about The ABC'S Of Types.

Conclusion

If you read to this point I really appreciate that, feel free to drop me a comment, corrections and suggestions as regards this series.

Thanks for reading🫂.