TypeScript Basics

Getting started with TypeScript.

Sep 2024

TypeScript is a superset of JavaScript, providing type safety and static type checking. It is a statically-typed language.

In statically typed languages, the data type of a variable is known at compile time, while in dynamically typed languages, the data type is assigned during runtime by the interpreter, depending on its value.

TypeScript is primarily a development tool, where the project still runs JavaScript.

To run a
.ts
program, follow these steps:

The first step involves transpiling, where the TypeScript compiler transpiles the TypeScript code to JavaScript. Transpiling is the process of converting the source code from one programming language to another. It is often used in web development, especially with languages like TypeScript and JSX, which are not directly supported by web browsers.

In TypeScript, primitive types such as string, number, and boolean are used to represent basic data types.

Note: JavaScript does not have a special runtime value for TypeScript types, so there's no equivalent to "int" or "float" - everything is simply number.

However, it's not always necessary to explicitly specify types. In some cases, TypeScript can infer types based on the assigned values. Overusing types can make the code verbose and less readable.

In situations where TypeScript cannot determine or is unsure about the type of a value, it marks the variable as
any
. However, using
any
is discouraged as it disables type checking. It's recommended to specify types explicitly or use the compiler flag
noImplicitAny
to flag implicit
any
types as errors.

Type annotations for functions are strong and recommended.

Syntax

Arrow Functions

Arrow functions provide a concise syntax for writing functions.

Default Value

Return Type

never

Some functions never return a value. The
never
type represents values that are never observed. In a return type, this means that the function throws an exception or terminates execution of the program.

Assigning type to an object

Bad behaviour of objects

When a function is called with an optional parameter, it throws an error. However, if an object with an optional property is created and assigned to a variable, calling the function with that variable does not result in an error.

Type Aliase is a name for any type. This is convenient, but it's common to want to use the same type more than once and refer to it by a single name.

Combining types

readonly & "?"(optional)

readonly
is used to make a property unchangeable, the value cannot be changed after it is set.
?
marks the property as optional.
To specify the type of an array like
[1,2,3]
, you can use the syntax
number[]
, this works for any type (e.g. string[]).
Union types are used when a value can be more than a single type. We use the vertical bar (
|
) to separate each type.

Note: Direct manipulation on individual types is not allowed because TS treats the union type as a new data type.

Tuples are typed arrays of pre-defined length and types for each index. The order of data type in each index should be maintained.

Array methods are allowed on tuples that violate type safety, so a good practice would be to make a tuple "readonly".

A special class that represents a group of constants, can be string or numeric.

First value is initialised to 0 by default then 1 is added to each additional value.

We can also set the value and have it auto increment from that.

Or we can initialise all the values.

Used to define shape/structure of objects. Interfaces are similar to type aliases, except they only apply to object types.

Interfaces can extend each other's definition. Extending simply means you are creating a new interface with same properties as that of the original interface, plus something new.

Declaration Syntax

Type: Types can be used to define simple types, union types, intersection types, and more.

Interface: Interfaces are typically used for defining object shapes.

Extending/Implementing

Type: Types can be used to create union or intersection types, but they cannot be extended or implemented.

Interface: Interfaces can extend other interfaces and can be implemented by classes.

Declaration Merging

Type: Types don't support declaration merging.

Interface: Interfaces support declaration merging, which means you can declare an interface multiple times, and their members will be merged.

  • Create
    tsconfig.json
    file
tsconfig.json
is a configuration file used by the TypeScript compiler (tsc) to specify compiler options and project settings for a TypeScript project. This file allows developers to define various settings such as compilation target, module system, output directory, and more.
  • Initialise Node Package Manager
  • Create
    dist
    and
    src
    folders.
  • Create
    index.html
    file and make it point to
    index.js
    in the
    dist
    folder by adding a script tag.
  • Create
    index.ts
    in the
    src
    folder.
  • Specify output directory in
    tsconfig.json
All TypeScript files will be transpiled to JavaScript files with the same name as the TypeScript files and stored in the
dist
directory.
  • Add content to your
    .ts
    file.
  • Compile and run
    .ts
    file.

This command runs TypeScript files in "watch mode", allowing the compiler to detect changes and recompile automatically.

TypeScript offers full support for the class keyword introduced in ES2015.

Here’s the most basic class - an empty one:

Fields

A field declaration creates a
public
writeable property on a class.

Getters & Setters

  • A getter method returns the property’s value. A getter is also called an accessor.
  • A setter method updates the property’s value. A setter is also known as a mutator.
  • A getter method starts with the keyword
    get
    and a setter method starts with the keyword
    set
    .

Note: A set accessor cannot have a return type annotation.

Interfaces can be implemented by classes.

Inheritance

It is the mechanism in which one class derives the properties of another class. In TypeScript a base class inherits a parent class using the
extends
keyword.
  • private
    keyword: private access modifier makes the field only accesssible inside a class.
  • protected
    keyword: protected members are only visible to subclasses of the class they’re declared in.
  • super
    keyword: It allows us to invoke constructor of parent class, call parent class methods within a subclass. The
    super
    keyword is useful for overriding and extending the behavior of methods defined in a parent class, especially when those methods are not declared as
    private
    .
Note: Constructors for derived class must contain a
super
call. Super must be called before accessing
this
in the constructor of a derived class.

Abstract classes

Define an abstract class in Typescript using the
abstract
keyword. Abstract classes are mainly for inheritance where other classes may derive from them. We cannot create an instance of an abstract class.

An abstract class typically includes one or more abstract methods or property declarations. The class which extends the abstract class must define all the abstract methods.

Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use.

They allow you to create reusable components (such as functions, classes, or interfaces) that can work with any data type while still providing type safety.

While using
any
is certainly generic in that it will cause the function to accept any and all types for the type of arg, we actually are losing the information about what that type was when the function returns. If we passed in a number, the only information we have is that any type could be returned.

Instead, we need a way of capturing the type of the argument in such a way that we can also use it to denote what is being returned. Here, we will use a type variable, a special kind of variable that works on types rather than values.

Custom generic interface

In the above example, when you define a generic type or interface like
Pair<T, U>
, T and U are placeholders for the actual types that will be used when instances of Pair are created. This allows you to create instances of Pair with different types for the first and second properties without having to define a separate interface for each combination of types.

Passing an array and using arrow functions

Extending a generic type

Generic class

Type narrowing in TypeScript refers to the process of refining the type of a variable within a certain block of code based on certain conditions. This helps TypeScript infer more specific types, improving type safety and enabling better code optimization.

While it might not look like much, there’s actually a lot going on under the covers here. Much like how TypeScript analyzes runtime values using static types, it overlays type analysis on JavaScript’s runtime control flow constructs like if/else, conditional ternaries, loops, truthiness checks, etc., which can all affect those types.

in
operator

The
in
operator is used for type narrowing, which means it helps narrow down the type of an object, based on wether a property exists within it. It's particularly useful when working with union or discriminated types.

instanceof
operator

The
instanceof
keyword is used to check whether an object is an instance of a particular class or constructor function. It returns true if the object is an instance of the specified class or its subclasses; otherwise, it returns false.

Type predicate

A type predicate is a way to assert the type of a variable within a conditional statement. It allows you to narrow down the type of a variable within a certain block of code, based on some condition.

In the
isFish
function, we define a type predicate
pet is Fish
, indicating that if the condition
(pet as Fish).swim !== undefined
is true, then pet is indeed a
Fish
. Within the
feedPet
function, when we call
isFish(pet)
, TypeScript narrows down the type of pet to Fish if the condition is met, allowing us to safely call
pet.swim()
without TypeScript throwing errors.

Discriminated Union & Exhaustive Checking

A discriminated union is a union type that utilizes a common property in each of its constituent types to allow for more precise type checking. This common property, typically called a "discriminant" or "tag", is used to discriminate between the different possible shapes within the union. (
kind
in this case)

Exhaustive checking refers to ensuring that all possible cases of the discriminated union are handled within a switch statement or if-else chain. This helps TypeScript catch errors where you might forget to handle a specific case, ensuring that your code is more robust.

The
never
type is used to indicate that a value should never occur. When used in the context of exhaustive checking with discriminated unions, it helps TypeScript ensure that all possible cases are handled, leaving no room for unexpected values.
Code

Feel free to browse the repository, raise issues, share your feedback, and contribute to the project.