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.
Section overview
4 resourcesCovers 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
typekeyword. 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
- Exercise 1: Create a type alias
StringArrayfor an array of strings. Use it to define a variablenamesand assign an array of names to it.
Solution:
```typescript
type StringArray = string[];
let names: StringArray = ['John', 'Jane', 'Jim'];
```
- Exercise 2: Create an interface
Employeewith propertiesid,name, anddepartment. Use it to define a functionprintEmployeethat 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article