Typescript

Is a superset of Javascript empowering it by:

  • Static typing

  • Decorators

  • Generic types

  • Tuples

  • Modules

  • Better OO support with abstract classes

  • Interfaces

  • Visibility modifiers

  • And more...

Needs to be transpiled to Javascript.

  • Compiler: Transforms code to low code (machine-code).

  • Transpiler: Transforms code to other high level languages (source-to-source).

Interoperability

Run js and ts in the same environment.

You can allow js to apply Typescript by creating a .d.ts file for a js file.

This file will have definitions typings for the js.

Exploring the tsconfig.json

Centralizes all the code static analysis and transpilation rules.

Options

  • incremental: For incremental transpilation, saving cache that will speedup future transpilations, specially for big projects. Essentialy just transpile the changed files.

  • target: Defines the version of Javascript that will be utilized as the transpilation target.

    • es5 | ECMA2009: Older version from 2009.

    • es6 | ECMA2015: Which targets the ECMA from 2015.

    • ECMA2016: Is the default one. (Higher compatibility)

      • Adds ** exponential, ...

    • ECMA2017:

      • Adds async, ...

    • ECMA2018:

      • Adds rest \ spread, ...

    • ECMA2019:

    • ECMA2020:

      • Adds ??

    • ...

    • Check https://node.green/ for details of ECMA versions support in Node.js

      • Node 16.x and greater versions, do support up to ECMA2023.

      • ESNext is the versions with Stage 3, Stage 2 and Stage 1 releases

  • module: Important to define the type of module system to be used. - CommonJS - ES Modules

  • include: Defines which are the directories that must be included in the transpilation.

  • exclude: Defines which directores must be excluded in transpilation.

  • outFile: Used for projects that run in the browser, defining a file that will concatenate all the transpiled files.

  • outDir: Defines the directory that the transpiled files will be placed after transpilation.

  • allowJS: To allow js files to part of the typescript environment.

  • strict: Turn on several type checkings like:

    • strictNullChecks: Allow or not to accept if things return null | undefined and what will receive them cannot handle it.

    • strictFunctionTypes: Allow or not to scrictly compare functions types to the detail when assigning functions to variables.

    • strictBindCallApply: Allow of not to pass to fn.call(), parameters to the function that are not of the same type.

    • strictPropertyInitialization: Allow or not to have class properties to be declared but not initialized.

    • noImplicitAny: Allow or not using variables without typing, that can be automatically impliced typed.

    • noImplicitThis: Allow or not, when you have this cases, where the this is not pointing to where you think it is.

    • useUnknowInCatchVariables: Allow or not to use unknown error types in catch.

    • alwaysStrict: Will always put use strict in the transpiled file.

      • Not used anymore in recent versions of ECMA.

    • allowUnreachableCode: Allow or not leaving code that is unreachable.

    • noUnusedLocals: Allow or not leaving unused declared variables.

    • noUncheckedIndexedAccess: Allow or not to access dynamic properties of objects with ..

      • For Ex.: [prop: string]: string.

      • The right way to access woulb be with [].

Types

Types can be inferred from values, but only at the variable declaration.

Type being inferred from the value:

A variable declared with no type will by default be of any type.

Built-in primitive types includes:

  • boolean

  • string

  • number: Representing integers and floats.

  • undefined

  • null

  • any

  • unknown

  • never

  • void

  • bigint

  • symbol

Common built-in JS Objects:

  • Date

  • Error

  • Array or []

  • Map

  • Set

  • Regexp

  • Promise

Type Literals:

  • Object: { field: number }

  • Function: (arg: number) => number

  • Arrays: Array<number> or number[]

  • Tuple: [number, number]

More details:

any

Very flexible and can accept any type.

Variable of any type may also receive different types values at any point.

unknown

Represents any value and while it is similar to any type, it is much safer because it's not legal to do anything with an unknown value.

This is useful when describing function types because you can describe functions that accept any value without having any values in your function body.

never

It is a return type, meaning that it never returns a value.

This should mean that the function either throws an exception or terminates execution of the program.

void

Represents the return value of functions which don't return a value.

Tuples

Are not a "type" per say, but it is a way to use the [] type, enforcing a size and adding values change constrains.

type

  • Used for type definitions, usually to reduce repetition.

  • It can be amost the same as interface, but it cannot be extendend.

  • They may not be extended but types can be merged.

interface

Types interface comparison checks can be faster.

  • Can be extended by declaring it multiple times, or merged with other interfaces.

  • Used to describe object shapes.

  • Can have function definitions. (Great to describe classes or contracts)

You can merge different interface into a type:

Extend it with extends:

It is also possible to extend via merging when the interfaces have the same name:

You can ensure a class conforms to an interface via implements.

Are a feature which allows for describing a value which could be one of a set of possible named constants.

It is NOT a type-level addition, but something added to the language and runtime.

Function Type

A way to declare the Function structure types (parameters and return).

You can generically say a variable is a function.

Or you can explicitly define it's params and return types.

Union Type

Describes a type which is one of many options. (These options are may be types or values)

Great for reducing and restricting the variable value options.

Template Union Types

A template string can be used to combine and manipulate text inside the type system.

Intersection Types

A way to merge/extend types. (&), as seen above.

Partial

Constructs a type with all properties of Type set to optional. This utility will return a type that represents all subsets of a given type. (So that you dont have to use ?:)

Required

Constructs a type consisting of all properties of Type set to required.

Pick

Constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type.

Omit

Constructs a type by picking all properties from Type and then removing Keys (String literal or union of string literals).

Conditional Types

Acts as if statements inside the type system. Created via generics, and then commonly used to reduce the number of options in a Type Union.

Generic Types

Are types that will hold a generic type, so that this type can change at runtime.

Will be the name inside <>, this name can be anything. (Conventionally it is used as T or R)

You can specify one or more generic types.

You may specify a default type for the generic if nothing was informed. (Otherwise Typescript will require you to specify a type)

You can constrain what types are accepted into the generic parameter with the extends keyword.

Mapped Types

Acts like a map statement for the type system, allowing an input type to change the structure of the new type.

Type Assertions

When you have information about the type of a value that Typescript can't know about.

Are removed by the compiler and don't affect the runtime behaviour of the code.

Sometimes this rule can be too conservative and will disallow more complex coercions that might be valid.

If this happens you can use two assertions, first to any or unkonwn then to the desired type.

Class

Structure

constructor section

constructor cannot be overloaded.

You could instead of declaring properties at the top, declare them at constructor's parameters section.

Or inside constructor section. But like this, you cannot assign visibility and other modifiers.

These properties would be declared as default ones. (public, not optional and writable)

And you must provide a value.

this in classes

The value of this inside a function depends on how the function is called or defined.

It is not garanteed to always be the class instance.

This problem is refered to as (losing this context).

Read more on Execution Context.

Defining methods with method() {}:

Declaring methods like this may implicate that the this context is lost and refers to another execution context, leading to runtime errors.

This happens on specific occasions like:

  • Passing the class method as Callback or storing it in a variable.

  • Using this in Event Listeners or Callbacks.

Defining methods with arrow functions:

Using arrow functions when declaring methods in classes is a good way to enforce that this will refer to the method's Class.

Since they only inherit the this from their enclosing lexical scope.

Binding this with .bind():

An alternative approach is to explicitly bind this using .bind(), allowing you to control this reference without having to use arrow functions.

Abstract classes

When declaring classes as not implementable, but as existing to be subclassed in the type system.

You dont instanciate an absctract class.

Can have absctract methods.

Difference of Abstract class and Interface

Abstract classes can have partial implementations. You can code inside them.

Interfaces cannot have code in them, they only describe typings and method names (Template Methods).

Decorators and Attributes

You can use decorators on classes, class methods, accessors, properties and parameters to methods.

Decorators

Ignoring decorators

@ts-ignore: Does not check the next line.

@ts-nocheck: Does not check the entire file.

Last updated