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.
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 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'
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'
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
Let's see some practical examples:
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 Rectangle {
width: number;
height: number;
}
function calculateArea(rectangle: Rectangle) {
return rectangle.width * rectangle.height;
}
calculateArea({ width: 5, height: 7 }); // returns 35
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
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.
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'];
```
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 class
Rectanglewith properties
widthand
heightand a method
getAreathat returns the area of the rectangle. Create an instance of the class and use it to call
getArea`.
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!