TypeScript / TypeScript Enums and Tuples

Type Definitions

In this tutorial, we will delve into the concept of Type Definitions in TypeScript. Type Definitions are a powerful feature that allow developers to define custom types.

Tutorial 1 of 4 4 resources in this section

Section overview

4 resources

Covers working with enums and tuples to define constant sets of values and fixed-length arrays.

Introduction

In this tutorial, we will explore the concept of Type Definitions in TypeScript. TypeScript, a statically typed superset of JavaScript, offers powerful features including Type Definitions, which allow us to create custom types. This feature is especially useful when we want to create complex types or want to make our code more descriptive and expressive.

By the end of this tutorial, you will have a good understanding of Type Definitions, how to create them, and how to use them in your TypeScript code.

Prerequisites: Basic understanding of TypeScript and its syntax, and a working TypeScript environment.

Step-by-Step Guide

TypeScript provides several ways to define custom types:

  • Type Aliases: We can create a new name for a type using the type keyword. It can represent a primitive, union, intersection, tuple, etc.

  • Interfaces: Interfaces in TypeScript are used to tell the compiler what the shape of the JS objects should look like.

  • Classes: Classes are a fundamental part of object-oriented programming, and TypeScript allows us to define types using classes.

Type Aliases

type StringOrNumber = string | number; // Union type

let data: StringOrNumber;
data = 'Hello'; // valid
data = 42; // valid
data = true; // error: Type 'boolean' is not assignable to type 'string | number'

Interfaces

interface User {
  id: string;
  name: string;
}

let user: User;
user = { id: '1', name: 'John Doe' }; // valid
user = { id: '2' }; // error: Property 'name' is missing in type '{ id: string; }' but required in type 'User'

Classes

class Car {
  brand: string;
  model: string;
  year: number;
}

let car: Car;
car = new Car(); // valid
car.brand = 'Toyota'; // valid
car.model = 'Corolla'; // valid
car.year = 2020; // valid

Code Examples

Let's see some practical examples:

Type Alias Example

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

function draw(point: Point) {
  // ...
}

draw({ x: 1, y: 2 }); // valid
draw({ x: 1 }); // error: Property 'y' is missing in type '{ x: number; }' but required in type 'Point'

Interface Example

interface Rectangle {
  width: number;
  height: number;
}

function calculateArea(rectangle: Rectangle) {
  return rectangle.width * rectangle.height;
}

calculateArea({ width: 5, height: 7 }); // returns 35

Class Example

class Circle {
  radius: number;

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

  getArea() {
    return Math.PI * Math.pow(this.radius, 2);
  }
}

let circle = new Circle(5);
console.log(circle.getArea()); // returns 78.53981633974483

Summary

In this tutorial, we have learned about Type Definitions in TypeScript, including type aliases, interfaces, and classes. These features allow us to create custom types, which can make our code more expressive and easier to understand.

Practice Exercises

  1. Exercise 1: Create a type alias StringArray for an array of strings. Use it to define a variable names and assign an array of names to it.

Solution:
```typescript
type StringArray = string[];

let names: StringArray = ['John', 'Jane', 'Jim'];
```

  1. Exercise 2: Create an interface Employee with properties id, name, and department. Use it to define a function printEmployee that prints an employee's details.

Solution:
```typescript
interface Employee {
id: number;
name: string;
department: string;
}

function printEmployee(employee: Employee) {
console.log(ID: ${employee.id}, Name: ${employee.name}, Department: ${employee.department});
}

printEmployee({ id: 1, name: 'John Doe', department: 'HR' }); // prints "ID: 1, Name: John Doe, Department: HR"
`` 3. **Exercise 3:** Create a classRectanglewith propertieswidthandheightand a methodgetAreathat returns the area of the rectangle. Create an instance of the class and use it to callgetArea`.

Solution:
```typescript
class Rectangle {
width: number;
height: number;

 constructor(width: number, height: number) {
   this.width = width;
   this.height = height;
 }

 getArea() {
   return this.width * this.height;
 }

}

let rectangle = new Rectangle(5, 7);
console.log(rectangle.getArea()); // prints 35
```

You can further practice these concepts by creating your own types and using them in different scenarios. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help