TypeScript utility functions example
TypeScript Classes and OOP : Exercise-24 with Solution
Write a TypeScript utility class with static methods for common utility functions, such as formatDate, generateRandomString, and capitalizeString. Each method should provide the respective utility functionality and be accessible without creating an instance of the class. Test the utility class by using its static methods to perform various tasks.
Sample Solution:
TypeScript Code:
Explanations:
In the exercise above -
- First, define a "Utility" class with static methods for "formatDate()", "generateRandomString()", and "capitalizeString()".
- The "formatDate()" method formats a given 'Date' object into a human-readable date string.
- The "generateRandomString()" method generates a random string of a specified length using alphanumeric characters.
- The "capitalizeString()" method capitalizes the first letter of a string.
- Finally test the "Utility" class by calling each static method with appropriate parameters and displaying the results.
Output:
"Formatted Date: October 9, 2023" "Random String: AZ9uUMw7vq" "Capitalized String: Hello world"
TypeScript Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.