Skip to content

Commit 20a13ab

Browse files
committed
fix: use function overload
1 parent 0a6e45d commit 20a13ab

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

apps/typescript/15-function-overload/src/app/app.component.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { createVehicle } from './vehicle.utils';
99
export class AppComponent {
1010
car = createVehicle('car', 'diesel');
1111
moto = createVehicle('moto', 'diesel');
12-
bus = createVehicle('bus', undefined, 20);
13-
boat = createVehicle('boat', undefined, 300, true);
12+
bus = createVehicle('bus', 20, true);
13+
boat = createVehicle('boat', 300);
1414
bicycle = createVehicle('bicycle');
1515
}

apps/typescript/15-function-overload/src/app/vehicle.utils.ts

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,28 +28,39 @@ interface Boat {
2828

2929
type Vehicle = Bicycle | Car | Moto | Bus | Boat;
3030

31+
export function createVehicle(type: 'bicycle'): Bicycle;
32+
export function createVehicle(type: 'car', fuel: Fuel): Car;
33+
export function createVehicle(type: 'moto', fuel: Fuel): Moto;
34+
export function createVehicle(
35+
type: 'bus',
36+
capacity: number,
37+
isPublicTransport: boolean,
38+
): Bus;
39+
export function createVehicle(type: 'boat', capacity: number): Boat;
3140
export function createVehicle(
3241
type: VehicleType,
33-
fuel?: Fuel,
34-
capacity?: number,
42+
fuelOrCapacity?: Fuel | number,
3543
isPublicTransport?: boolean,
3644
): Vehicle {
3745
switch (type) {
3846
case 'bicycle':
3947
return { type };
4048
case 'car':
4149
case 'moto':
42-
if (!fuel) throw new Error(`fuel property is missing for type ${type}`);
43-
return { fuel, type };
50+
if (!fuelOrCapacity || !isFuel(fuelOrCapacity))
51+
throw new Error(`fuel property is missing for type ${type}`);
52+
return { fuel: fuelOrCapacity, type };
4453
case 'boat':
45-
if (!capacity)
54+
if (!fuelOrCapacity || isFuel(fuelOrCapacity))
4655
throw new Error(`capacity property is missing for type boat`);
47-
return { capacity, type };
56+
return { capacity: fuelOrCapacity, type };
4857
case 'bus':
49-
if (!capacity)
58+
if (!fuelOrCapacity || isFuel(fuelOrCapacity))
5059
throw new Error(`capacity property is missing for type bus`);
5160
if (!isPublicTransport)
5261
throw new Error(`isPublicTransport property is missing for type bus`);
53-
return { capacity, isPublicTransport, type };
62+
return { capacity: fuelOrCapacity, isPublicTransport, type };
5463
}
5564
}
65+
66+
const isFuel = (fuel: Fuel | number): fuel is Fuel => typeof fuel !== 'number';

0 commit comments

Comments
 (0)