Typescript Tutorials for Beginners + Advanced Tutorials

As a SharePoint developer, you should learn TypeScript, which is essential for developing SharePoint Framework (SPFx) solutions. TypeScript provides features such as type inference and strict type checking, which can help catch errors before the code is run. I have provided a list of TypeScript tutorials for beginners and advanced developers. If you are starting to learn Typescript, check out the beginner’s tutorial list. Check out the list of advanced Typescript tutorials if you are an advanced user who knows Typescript.

What is Typescript?

TypeScript is an open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, meaning that any valid JavaScript code is also valid TypeScript code.

The main feature that distinguishes TypeScript from JavaScript is its static type system. TypeScript introduces optional static typing to JavaScript, which can help developers catch errors early in the development process, improve code quality, and enhance the maintainability of large codebases.

Advantages of TypeScript

TypeScript is primarily used for developing large-scale applications where the codebase can become complex and difficult to manage. Here are a few advantages of Typescript.

  • TypeScript helps developers by adding static typing to JavaScript. This feature allows them to specify types for variables and functions, catching errors during development.
  • Developers find improved tooling a strong advantage. Features like autocompletion and type-checking make the coding process smoother and more efficient.
  • TypeScript integrates seamlessly with existing JavaScript projects. Developers familiar with JavaScript can start using TypeScript without learning new programming fundamentals.
  • TypeScript projects often have better documentation. The static types make the code easier to read and maintain.
  • By providing type safety, TypeScript helps teams catch bugs early. This leads to more robust and reliable code. Additionally, these features build confidence in the final product.
  • Teams find that using TypeScript makes codebases easier to scale. As the project grows, maintaining code becomes simpler, allowing for easier collaboration and fewer errors.

Set up the TypeScript Environment

As a developer, the next thing you should learn is how to set up the development environment for Typescript.

Setting up TypeScript requires a few steps: users need to install TypeScript, set up the tsconfig.json file, and understand the compilation process from TypeScript to JavaScript.

Download and Installing TypeScript

To start using TypeScript, install Node.js first. It provides the environment to run the TypeScript compiler. After installing Node.js, open the terminal or command prompt.

Execute the following command to install TypeScript globally:

npm install -g typescript

This command uses Node Package Manager (NPM) to download TypeScript and makes it accessible from anywhere on the system.

To check if the installation was successful, type:

tsc --version

This should display the installed version of TypeScript if everything is set up correctly.

Install an IDE like Visual Studio Code

Visual Studio Code (VS Code) is a popular, open-source code editor developed by Microsoft that is widely used for TypeScript development due to its excellent TypeScript support.

Visual Studio Code is highly recommended for Typescript development. You can download it from the official website.

VS Code comes with an integrated TypeScript language service that is out-of-the-box, providing features such as IntelliSense, which offers smart code completions based on variable types, function definitions, and imported modules.

Another advantage of using VS Code for TypeScript development is its powerful debugging capabilities. VS Code includes a built-in debugger that allows developers to set breakpoints, step through code, inspect variables, and call stacks. This makes it easier to diagnose and fix issues in TypeScript applications.

Configure the tsconfig.json File

After installing TypeScript, create a tsconfig.json file in the project directory. This file is crucial for setting compiler options and how the project treats TypeScript files.

Use the command for initialization:

tsc --init

This generates a default tsconfig.json file, which can be customized. Important settings include target (for specifying the JavaScript version), module (to set the module system), and outDir (to define the directory for compiled JavaScript files).

This file contains compiler options and other settings. Here is what it looks like:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

Understand the Compilation Process

TypeScript is a superset of JavaScript, but it needs to be compiled into JavaScript. This conversion is handled by the TypeScript compiler, translated from .ts files into .js files.

Run the command below to compile TypeScript:

tsc

This translates the code and produces JavaScript output in the specified directory. The watch mode can be used to recompile automatically whenever .ts files change, by using:

tsc --watch

Basic TypeScript Types

TypeScript offers a range of basic types to help developers reduce errors in their code. As a developer, you should understand these types for more efficient coding, fewer bugs, and more robust programs.

Primitive Types: String, Number, and Boolean

TypeScript includes primitive types like stringnumber, and boolean. The string type is used for textual data. For example, let userName: string = "Alice";.

The number type is for all kinds of numeric values, like let userAge: number = 25;Boolean is for true or false values, such as:

let isLoggedIn: boolean = true;

These types ensure that values are used consistently, catching errors early during development.

The Any, Unknown, and Never Types

The any type can hold any value, providing flexibility. However, overusing it may bypass types, leading to potential errors:

let variable: any = 5; variable = "text";

The unknown type is safer, requiring type checking before use:

let input: unknown = "hello"; 
if (typeof input === "string") {
  console.log(input.toUpperCase());
}

The never type is for functions that do not return, such as those that always throw an error or have an infinite loop.

Array and Tuple Types

Arrays in TypeScript store multiple values of the same type. The syntax is straightforward:

let fruits: string[] = ["apple", "banana"]

Tuples, on the other hand, hold a fixed number of elements of specific types: let tuple: [string, number] = ["age", 30];. This ensures that the structure stays consistent, reducing errors due to unexpected data structures.

Enum and Literal Types

Enums represent a set of named constants. They make code readable and reduce potential errors:

enum Direction {
  Up,
  Down,
  Left,
  Right
}

Literal types allow setting a specific set of values to a variable: let answer: "yes" | "no" = "yes";. This enforces the use of predefined values, enhancing code accuracy.

Type Assertions and Aliases

Type assertions let developers override TypeScript’s inferred type for a variable. It’s like telling TypeScript to trust the developer’s input:

let code: any = "123";
let employeeCode = <number>code;

Type aliases give a type a new name, shortening complex types and improving readability. For instance:

type User = {
  name: string;
  age: number;
};

These tools help organize code efficiently while preserving type safety.

Important Typescript Concepts

Here are some important concepts in Typescript, that you should know as a developer.

Interfaces

Interfaces in TypeScript define the structure of an object. They help in defining contracts within your code and ensuring that objects adhere to specific structures.

interface Person {
  firstName: string;
  lastName: string;
}

function greeter(person: Person) {
  return "Hello, " + person.firstName + " " + person.lastName;
}

let user = { firstName: "John", lastName: "Doe" };

console.log(greeter(user));

Classes

TypeScript supports object-oriented programming with classes. You can define classes with properties and methods.

class Greeter {
  greeting: string;

  constructor(message: string) {
    this.greeting = message;
  }

  greet() {
    return "Hello, " + this.greeting;
  }
}

let greeter = new Greeter("world");

console.log(greeter.greet());

Modules

Modules in TypeScript help in organizing code into reusable components. You can export and import modules using the export and import keywords.

// math.ts
export function add(x: number, y: number): number {
  return x + y;
}

// app.ts
import { add } from "./math";

console.log(add(2, 3));

Generics

Generics allow you to create reusable components that work with any data type in Typescript. Here is an example.

function identity<T>(arg: T): T {
  return arg;
}

let output1 = identity<string>("myString");
let output2 = identity<number>(100);

Type Inference

TypeScript can infer the types of variables based on their values. This feature reduces the need for explicit type annotations.

let x = 3; // inferred as number

Type Aliases

Type aliases allow you to create a new name for a type. This is useful for simplifying complex type definitions.

type Point = {
  x: number;
  y: number;
};

let point: Point = { x: 10, y: 20 };

Union and Intersection Types

Union types allow a variable to hold multiple types, while intersection types combine multiple types into one.

function printId(id: number | string) {
  console.log("Your ID is: " + id);
}

type Person = {
  name: string;
};

type Employee = Person & {
  employeeId: number;
};

Decorators

Decorators are a powerful feature in TypeScript that allows you to modify the behavior of classes and their members. They are often used in frameworks like Angular.

function sealed(constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

@sealed
class Greeter {
  greeting: string;

  constructor(message: string) {
    this.greeting = message;
  }

  greet() {
    return "Hello, " + this.greeting;
  }
}

TypeScript Keywords

TypeScript, being a superset of JavaScript, inherits many of its keywords while also introducing several new ones to support its unique features. These keywords are crucial in defining the structure, behavior, and type safety of TypeScript code. Below are some of the most important TypeScript keywords and their functions.

let and const

TypeScript, like modern JavaScript (ES6+), uses let and const for variable declarations. The let keyword allows you to declare block-scoped variables, which helps prevent issues related to variable hoisting and scope leakage.

On the other hand, const is used to declare constants, ensuring that the variable’s value cannot be reassigned after its initial assignment.

let count: number = 10;
const name: string = "Alice";

type and interface

TypeScript introduces the type and interface keywords to define custom types and interfaces. These constructs are essential for describing the shape and structure of objects, enabling type safety and code readability.

  • type: Used to create type aliases, simplifying complex type definitions and making code more readable.
type Point = {
  x: number;
  y: number;
};

let p: Point = { x: 10, y: 20 };
  • interface: Defines a contract for objects, specifying the properties and methods that an object must implement. Classes can extend and implement interfaces.
interface Person {
  name: string;
  age: number;
}

class Employee implements Person {
  constructor(public name: string, public age: number, public position: string) {}
}

enum

The enum keyword allows you to define a set of named constants, making code more readable and maintainable. Enums are particularly useful for representing a collection of related values, such as days of the week or states in a state machine.

enum Color {
  Red,
  Green,
  Blue
}

let c: Color = Color.Green;

readonly

The readonly keyword in Typescript is used to mark properties of an object as immutable. Once a property is defined as readonly, its value cannot be changed after initialization. This is useful for creating immutable data structures and ensuring that certain properties remain constant throughout the program’s lifecycle.

class Circle {
  readonly radius: number;

  constructor(radius: number) {
    this.radius = radius;
  }
}

let circle = new Circle(5);
// circle.radius = 10; // Error: Cannot assign to 'radius' because it is a read-only property.

abstract

The abstract keyword is used to define abstract classes and methods in Typescript. An abstract class cannot be instantiated directly and is intended to be subclassed. Abstract methods, defined within an abstract class, must be implemented by derived classes.

abstract class Animal {
  abstract makeSound(): void;

  move(): void {
    console.log("Moving...");
  }
}

class Dog extends Animal {
  makeSound(): void {
    console.log("Bark!");
  }
}

let dog = new Dog();
dog.makeSound(); // Output: Bark!
dog.move(); // Output: Moving...

namespace

The namespace keyword is used to organize code into logical groups, preventing name collisions and improving code modularity. Namespaces are particularly useful in large applications where multiple modules and libraries are used.

namespace Geometry {
  export class Circle {
    constructor(public radius: number) {}

    area(): number {
      return Math.PI * this.radius * this.radius;
    }
  }
}

let circle = new Geometry.Circle(5);
console.log(circle.area()); // Output: 78.53981633974483

as

The as keyword in Typescript is used for type assertions, allowing developers to override TypeScript’s inferred type system. This is useful when you know more about the type of a variable than TypeScript can infer.

let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;

Here are some Typescript keyword tutorials:

Typescript Tutorials for Beginners and Experienced Developers

Now, here is the list of Typescript tutorials for beginners as well as for experienced developers.

>