TypeScript type aliases for improved readability
TypeScript Basic: Exercise-7 with Solution
Write a TypeScript program that creates type aliases for complex data types such as objects or custom types. Use them to define variables and explain how they improve code readability.
Sample Solution:
TypeScript Code:
// Define a type alias for a user object
type Student = {
id: number;
studentname: string;
email: string;
};
// Define a type alias for a point in 2D space
type Point = {
x: number;
y: number;
};
// Create variables using the type aliases
const student1: Student = {
id: 1,
studentname: "ginny_millaray",
email: "[email protected]",
};
const student2: Student = {
id: 2,
studentname: "endika_keeva",
email: "[email protected]",
};
const originPoint: Point = {
x: 0,
y: 0,
};
// Functions that use the type aliases
function printStudentInfo(student: Student) {
console.log(`Student ID: ${student.id}`);
console.log(`Studentname: ${student.studentname}`);
console.log(`Email: ${student.email}`);
}
function calculateDistance(point1: Point, point2: Point): number {
const dx = point1.x - point2.x;
const dy = point1.y - point2.y;
return Math.sqrt(dx * dx + dy * dy);
}
// Using the type aliases to improve code readability
console.log("Student 1:");
printStudentInfo(student1);
console.log("\nStudent 2:");
printStudentInfo(student2);
console.log("\nDistance from origin:");
console.log(calculateDistance(originPoint, { x: 3, y: 4 }));
Explanations:
In the exercise above -
- First, we define two type aliases: 'Student' and 'Point'. 'Student' represents a student object with 'id', 'studentname', and 'email' properties, and 'Point' represents a point in 2D space with x and y coordinates.
- We create variables 'student', 'student2', and 'origin' using these type aliases. The type annotations make it clear what kind of data each variable should hold.
- We define functions :printStudentInfo()" and "calculateDistance()" that accept parameters with the corresponding type aliases, improving code readability and ensuring that the expected data structure is passed as an argument.
- Finally, we use the type aliases to improve code readability when calling these functions and working with the variables.
Output:
"Student 1:" "Student ID: 1" "Studentname: ginny_millaray" "Email: [email protected]" Student 2:" "Student ID: 2" "Studentname: endika_keeva" "Email: [email protected]" Distance from origin:" 5
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript type conversion example.
Next: TypeScript array operations: Add, remove, iterate.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics