diff --git a/apps/typescript/15-function-overload/src/app/app.component.ts b/apps/typescript/15-function-overload/src/app/app.component.ts index 3ea2a7131..d8843095b 100644 --- a/apps/typescript/15-function-overload/src/app/app.component.ts +++ b/apps/typescript/15-function-overload/src/app/app.component.ts @@ -2,14 +2,13 @@ import { Component } from '@angular/core'; import { createVehicle } from './vehicle.utils'; @Component({ - standalone: true, selector: 'app-root', template: ``, }) export class AppComponent { car = createVehicle('car', 'diesel'); moto = createVehicle('moto', 'diesel'); - bus = createVehicle('bus', undefined, 20); - boat = createVehicle('boat', undefined, 300, true); + bus = createVehicle('bus', 20, true); + boat = createVehicle('boat', 300); bicycle = createVehicle('bicycle'); } diff --git a/apps/typescript/15-function-overload/src/app/vehicle.utils.ts b/apps/typescript/15-function-overload/src/app/vehicle.utils.ts index bec95c08d..3240c1afa 100644 --- a/apps/typescript/15-function-overload/src/app/vehicle.utils.ts +++ b/apps/typescript/15-function-overload/src/app/vehicle.utils.ts @@ -28,10 +28,21 @@ interface Boat { type Vehicle = Bicycle | Car | Moto | Bus | Boat; +// Overloads +export function createVehicle(type: 'bicycle'): Bicycle; +export function createVehicle(type: 'car', fuel: Fuel): Car; +export function createVehicle(type: 'moto', fuel: Fuel): Moto; +export function createVehicle( + type: 'bus', + capacity: number, + isPublicTransport: boolean, +): Bus; +export function createVehicle(type: 'boat', capacity: number): Boat; + +// Implementation export function createVehicle( type: VehicleType, - fuel?: Fuel, - capacity?: number, + fuelOrCapacity?: Fuel | number, isPublicTransport?: boolean, ): Vehicle { switch (type) { @@ -39,17 +50,22 @@ export function createVehicle( return { type }; case 'car': case 'moto': - if (!fuel) throw new Error(`fuel property is missing for type ${type}`); - return { fuel, type }; + if (!fuelOrCapacity || !isFuel(fuelOrCapacity)) + throw new Error(`fuel property is missing for type ${type}`); + return { fuel: fuelOrCapacity, type }; case 'boat': - if (!capacity) + if (!fuelOrCapacity || isFuel(fuelOrCapacity)) throw new Error(`capacity property is missing for type boat`); - return { capacity, type }; + return { capacity: fuelOrCapacity, type }; case 'bus': - if (!capacity) + if (!fuelOrCapacity || isFuel(fuelOrCapacity)) throw new Error(`capacity property is missing for type bus`); if (!isPublicTransport) throw new Error(`isPublicTransport property is missing for type bus`); - return { capacity, isPublicTransport, type }; + return { capacity: fuelOrCapacity, isPublicTransport, type }; } } + +function isFuel(fuelOrCapacity: Fuel | number): fuelOrCapacity is Fuel { + return typeof fuelOrCapacity === 'string'; +}