Lesson
Basic Explanation of Typescript Generics
A very basic explanation of generic function arguments
- Access
- Pro
- Transcript
- Available
This TypeScript tutorial explains how to use generics, allowing for different types to be passed as arguments. It discusses the use of shorthand syntax in generics and illustrates with examples. This method is useful for library creation, providing type safety and control to the user.
interface PhotoMetadata<T> {
title: string;
takenAt: Date;
customData: T;
}
// Function that processes a photo with custom metadata
function processPhoto<T>(photo: PhotoMetadata<T>): {
processedTitle: string;
daysSinceCapture: number;
customDataSummary: T;
} {
const today = new Date();
const daysSinceCapture = Math.floor(
(today.getTime() - photo.takenAt.getTime()) / (1000 * 60 * 60 * 24)
);
return {
processedTitle: photo.title.toUpperCase(),
daysSinceCapture,
customDataSummary: photo.customData
};
}
// Example usage with different custom data shapes
type CameraSettings = {
iso: number;
aperture: string;
shutterSpeed: string;
}
type LocationData = {
latitude: number;
longitude: number;
locationName: string;
}
// Using with camera settings
const photoWithCamera: PhotoMetadata<CameraSettings> = {
title: "Sunset at beach",
takenAt: new Date('2024-01-15'),
customData: {
iso: 100,
aperture: "f/2.8",
shutterSpeed: "1/1000"
}
};
// Using with location data
const photoWithLocation: PhotoMetadata<LocationData> = {
title: "Mountain vista",
takenAt: new Date('2024-02-01'),
customData: {
latitude: 45.5231,
longitude: -122.6765,
locationName: "Mount Hood"
}
};
const processedCameraPhoto = processPhoto(photoWithCamera);
const processedLocationPhoto = processPhoto(photoWithLocation);
processedCameraPhoto.customDataSummary.iso
processedLocationPhoto.customDataSummary.longitude