What is TypeScript Example? A Comprehensive Guide to TypeScript [2023]

Firewood shed in winter

If you have been working with JavaScript, you may have heard about TypeScript. It's a superset of JavaScript that provides static typing, classes, interfaces, and other advanced features to help make your JavaScript code more scalable and maintainable. In this article, we will take a deep dive into TypeScript and explore various examples to help you understand how it works and why it's beneficial.

Table of Contents

Introduction

TypeScript is a language that helps you write clean and organized code. It provides features such as static typing, which catches errors at compile-time rather than runtime, making it easier to catch bugs early in the development process. TypeScript also supports modern JavaScript syntax and includes additional features like classes, interfaces, and modules, which are not yet fully supported in all browsers.

To get started with TypeScript, you need to install the TypeScript compiler (tsc) globally on your machine. Once installed, you can write TypeScript code in .ts files, which will be transpiled into plain JavaScript files (*.js files) that can be executed by the JavaScript runtime.

Getting Started with TypeScript

To create a TypeScript project, you can follow these steps:

  1. Install TypeScript globally on your machine by running the command npm install -g typescript.

  2. Create a new directory for your project.

  3. Inside the project directory, create a new file called index.ts and open it in a code editor.

  4. Write some TypeScript code in the index.ts file, for example:

    function greet(name: string) {
      console.log(`Hello, ${name}!`);
    }
    
    greet("TypeScript");
    
  5. Open a terminal or command prompt and navigate to the project directory.

  6. Run the TypeScript compiler by executing the command tsc index.ts.

  7. The compiler will generate a JavaScript file called index.js in the same directory.

  8. Run the JavaScript file by executing the command node index.js.

  9. You should see the output Hello, TypeScript! in the console.

Congratulations! You have successfully created and executed your first TypeScript program. Now let's explore some of the essential features of TypeScript.

Types by Inference

Time to hit the books

One of the key features of TypeScript is its ability to infer types. When you declare a variable without specifying its type, TypeScript will automatically infer the type based on the initial value assigned to it. This allows you to write code without explicitly specifying types while still benefiting from static type checking.

Here's an example:

let message = "Hello, TypeScript!";                // Type inference: `message` is of type `string`
let count = 10;                                    // Type inference: `count` is of type `number`
let isActive = true;                               // Type inference: `isActive` is of type `boolean`

message = 42;                                     // Error: Type '42' is not assignable to type 'string'
count = "hello";                                  // Error: Type '"hello"' is not assignable to type 'number'
isActive = 0;                                     // Error: Type '0' is not assignable to type 'boolean'

In the above example, the types of the variables message, count, and isActive are inferred based on their initial values. Any attempts to assign a value of a different type will result in a type error.

Defining Types

In addition to type inference, TypeScript allows you to define your own types using interfaces, classes, and type aliases. This enables you to create custom data structures and define the shape and behavior of your objects.

Interfaces

Interfaces in TypeScript define the contract for an object. They specify the properties and methods that an object must have to conform to the interface.

Here's an example of defining an interface for a Person object:

interface Person {
  name: string;
  age: number;
  greet(): void;
}

const john: Person = {
  name: "John Doe",
  age: 30,
  greet() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
};

john.greet();  // Output: Hello, my name is John Doe and I'm 30 years old.

In this example, the Person interface defines the required properties name and age, as well as the method greet(). The variable john implements the Person interface and provides the necessary properties and method.

Classes

Classes in TypeScript provide a convenient way to define objects with properties and methods. They encapsulate data and behavior into reusable components and support inheritance and polymorphism.

Here's an example of defining a class for a Circle object:

class Circle {
  radius: number;

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

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

const circle = new Circle(5);
console.log(circle.getArea());  // Output: 78.53981633974483

In this example, the Circle class has a radius property and a getArea() method. When we create a new instance of the Circle class and call the getArea() method, it calculates and returns the area of the circle.

Type Aliases

Type aliases allow you to create reusable type definitions. They can be used to give a more descriptive name to an existing type or to define complex types.

Here's an example of using a type alias to define a custom type:

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

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

In this example, the Point type alias represents an object with x and y properties. We then declare a variable point of type Point and assign it an object with the appropriate properties.

Composing Types

TypeScript allows you to compose types by combining them using union types, intersection types, and generics. This enables you to create flexible and reusable type definitions.

Union Types

Union types in TypeScript allow a value to have more than one potential type. You can use the | symbol to define a union type.

Here's an example of using a union type for a variable that can hold either a string or a number:

let myVariable: string | number;

myVariable = "Hello";    // Valid assignment
myVariable = 42;         // Valid assignment
myVariable = true;       // Error: Type 'true' is not assignable to type 'string | number'

In this example, myVariable can be assigned a value of type string or number. Any other type assignment will result in a type error.

Intersection Types

Intersection types in TypeScript allow you to combine multiple types into one. You can use the & symbol to define an intersection type.

Here's an example of using an intersection type for a variable that combines properties from multiple interfaces:

interface Printable {
  print(): void;
}

interface Loggable {
  log(): void;
}

function createLogger(): Printable & Loggable {
  return {
    print() {
      console.log("Printing...");
    },
    log() {
      console.log("Logging...");
    }
  };
}

const logger = createLogger();
logger.print();   // Output: Printing...
logger.log();     // Output: Logging...

In this example, the createLogger() function returns an object that conforms to both the Printable and Loggable interfaces. The returned object can be assigned to a variable that has an intersection type of Printable & Loggable, allowing it to call both the print() and log() methods.

Generics

Generics in TypeScript allow you to create reusable components that can work with different types. They provide a way to parameterize types and enable type checking and code reuse.

Here's an example of creating a generic function to reverse an array:

function reverse<T>(array: T[]): T[] {
  return array.reverse();
}

const numbers = [1, 2, 3, 4, 5];
const reversedNumbers = reverse(numbers);

console.log(reversedNumbers);  // Output: [5, 4, 3, 2, 1]

In this example, the reverse() function is defined with a generic type parameter T, which represents the element type of the array. The function can be called with an array of any type, and it will return the reversed array of the same type.

Structural Type System

TypeScript uses a structural type system, which means that type compatibility is based on the shape or structure of a type, rather than its name or origin. This allows you to create more flexible and reusable code.

For example, consider the following code:

interface Shape {
  name: string;
}

interface Circle {
  name: string;
  radius: number;
}

function logShapeName(shape: Shape) {
  console.log(shape.name);
}

const circle: Circle = {
  name: "Circle",
  radius: 5
};

logShapeName(circle);   // Output: Circle

In this example, even though the circle object has a more specific type (Circle), it is still compatible with the Shape interface because it has the required name property. This allows us to pass the circle object to a function that accepts a Shape parameter.

TypeScript FAQ

What is the difference between JavaScript and TypeScript?

JavaScript is a dynamic scripting language used for developing web applications. It is widely supported by all web browsers and provides a flexible and easy-to-use syntax. However, JavaScript lacks certain features and tools that can make large-scale application development more manageable.

TypeScript, on the other hand, is a superset of JavaScript that adds static typing, classes, interfaces, and other advanced features. It provides a more robust development experience by catching errors at compile-time, improving tooling support, and enabling better code organization and maintainability.

In summary, TypeScript enhances JavaScript by adding static typing and other language features to help build scalable and maintainable applications.

How to write TypeScript code?

To write TypeScript code, you need to follow these steps:

  1. Install TypeScript globally on your machine by running the command npm install -g typescript.
  2. Create a new .ts file or convert an existing JavaScript file to TypeScript by changing its extension to .ts.
  3. Write TypeScript code using the additional language features provided by TypeScript, such as static typing, classes, interfaces, and modules.
  4. Run the TypeScript compiler (tsc) to transpile your TypeScript code into JavaScript.

What are the three main simple types in TypeScript?

The three main simple types in TypeScript are:

  1. number – Represents numeric values. It includes both integers and floating-point numbers.
  2. string – Represents textual data. It can be enclosed in single or double quotes.
  3. boolean – Represents a logical value, either true or false.

These simple types are the building blocks for more complex types and can be used to define variables, function parameters, and return types.

Quick Tips and Facts

  • TypeScript is compatible with all existing JavaScript libraries and frameworks.
  • The TypeScript compiler allows you to configure strictness levels to catch potential errors and enforce best practices.
  • TypeScript supports modern JavaScript features such as async/await, destructuring, and arrow functions.
  • Many popular frameworks and tools, such as Angular, Vue.js, and NestJS, have excellent TypeScript support.
  • TypeScript has excellent tooling support, including autocompletion, refactoring, and static analysis with tools like Visual Studio Code.

Jacob
Jacob

Jacob is a software engineer with over 2 decades of experience in the field. His experience ranges from working in fortune 500 retailers, to software startups as diverse as the the medical or gaming industries. He has full stack experience and has even developed a number of successful mobile apps and games.

Articles: 147

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.