- Typescript Daily
- Posts
- 10 commonly encountered real-world scenarios. Solved using typescript.
10 commonly encountered real-world scenarios. Solved using typescript.
Hello Typescript Daily readers!
In today’s article, we look at 10 of the most useful real-world snippets using typescript. This involves scenarios ranging from making an API call to safely parsing a JSON file.
Let’s get started!
1. Fetching Data from an API with Axios:
import axios from 'axios';
async function fetchData(): Promise<any> {
try {
const response = await axios.get('https://api.example.com/data');
return response.data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
}
2. Debouncing Input for Search Functionality:
function debounce(func: Function, delay: number): Function {
let timeoutId: NodeJS.Timeout;
return (...args: any[]) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func(...args);
}, delay);
};
}
// Usage:
const search = debounce((query: string) => {
// Perform search with query
}, 300);
3. Mapping an Array of Objects to a Different Structure:
interface User {
id: number;
firstName: string;
lastName: string;
}
function mapUsers(users: User[]): { id: number; fullName: string }[] {
return users.map(user => ({
id: user.id,
fullName: `${user.firstName} ${user.lastName}`
}));
}
4. Generating a Random String:
function generateRandomString(length: number): string {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
5. Type-Safe Local Storage Wrapper:
function setItem<T>(key: string, value: T): void {
localStorage.setItem(key, JSON.stringify(value));
}
function getItem<T>(key: string): T | null {
const data = localStorage.getItem(key);
return data ? JSON.parse(data) : null;
}
6. Validating Email Format:
function isValidEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
7. Calculating Age from Birthdate:
function calculateAge(birthdate: Date): number {
const today = new Date();
let age = today.getFullYear() - birthdate.getFullYear();
const monthDiff = today.getMonth() - birthdate.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthdate.getDate())) {
age--;
}
return age;
}
8. Capitalizing the First Letter of a String:
function capitalizeFirstLetter(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
9. Checking Object Type in a Guard Function:
function isCar(vehicle: any): vehicle is { make: string; model: string; year: number } {
return 'make' in vehicle && 'model' in vehicle && 'year' in vehicle;
}
10. Parsing JSON Safely:
function parseJSON(jsonString: string): any {
try {
return JSON.parse(jsonString);
} catch (error) {
console.error('Error parsing JSON:', error);
return null;
}
}
The above snippets cover some of the commonly encountered real-world scenarios. Of course, they only touch on the basic version of the features. You can certainly extend this and add more logic specific to your use cases.
Hope this was of some use to you!
Stay tuned for tomorrow’s article on an entirely different topic.
Reply