#Overloads versus Function overloading,
1 messages · Page 1 of 1 (latest)
// Common types
type Animal = {
name: string;
age: number;
};
type DogSound = { type: 'bark'; volume: 'loud' | 'soft' };
type CatSound = { type: 'meow'; pitch: 'high' | 'low' };
type BirdSound = { type: 'chirp'; melody: string[] };
type SoundOptions = {
species: 'dog' | 'cat' | 'bird';
mood?: 'happy' | 'sad';
timeOfDay?: 'morning' | 'night';
};
// Approach 1: Conditional Types
type PetSound<T> = T extends { species: 'dog' }
? DogSound
: T extends { species: 'cat' }
? CatSound
: T extends { species: 'bird' }
? BirdSound
: never;
function makeSound<T extends SoundOptions>(
pet: Animal,
options: T
): Promise<PetSound<T>> {
// Implementation that handles all cases in one function
if (options.species === 'dog') {
return Promise.resolve({
type: 'bark',
volume: options.mood === 'happy' ? 'loud' : 'soft'
} as PetSound<T>);
} else if (options.species === 'cat') {
return Promise.resolve({
type: 'meow',
pitch: options.timeOfDay === 'night' ? 'high' : 'low'
} as PetSound<T>);
} else {
return Promise.resolve({
type: 'chirp',
melody: options.mood === 'happy' ? ['tweet', 'tweet'] : ['chirp']
} as PetSound<T>);
}
}