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:
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: ginny@example.com" Student 2:" "Student ID: 2" "Studentname: endika_keeva" "Email: endika@example.com" Distance from origin:" 5
TypeScript Editor:
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.