feat(challenge15): function overload

This commit is contained in:
thomas laforge
2023-01-19 22:16:17 +01:00
parent 3bbd4cf4dd
commit fa53d48b09
13 changed files with 276 additions and 0 deletions

View File

@@ -0,0 +1,14 @@
import { Component } from '@angular/core';
import { createVehicle } from './teacher.utils';
@Component({
standalone: true,
selector: 'app-root',
template: ``,
})
export class AppComponent {
car = createVehicle('car', 'diesel');
bus = createVehicle('bus', undefined, 20);
boat = createVehicle('boat', undefined, 300, true);
bicycle = createVehicle('bicycle');
}

View File

@@ -0,0 +1,55 @@
type VehicleType = 'bus' | 'car' | 'moto' | 'bicycle' | 'boat';
type Fuel = 'diesel' | 'petrol' | 'electric';
interface Bicycle {
type: 'bicycle';
}
interface Car {
fuel: Fuel;
type: 'car';
}
interface Moto {
fuel: Fuel;
type: 'moto';
}
interface Bus {
capacity: number;
isPublicTransport: boolean;
type: 'bus';
}
interface Boat {
capacity: number;
type: 'boat';
}
type Vehicle = Bicycle | Car | Moto | Bus | Boat;
export function createVehicle(
type: VehicleType,
fuel?: Fuel,
capacity?: number,
isPublicTransport?: boolean
): Vehicle {
switch (type) {
case 'bicycle':
return { type };
case 'car':
case 'moto':
if (!fuel) throw new Error(`fuel property is missing for type ${type}`);
return { fuel, type };
case 'boat':
if (!capacity)
throw new Error(`capacity property is missing for type boat`);
return { capacity, type };
case 'bus':
if (!capacity)
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 };
}
}

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Overload</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<app-root></app-root>
</body>
</html>

View File

@@ -0,0 +1,4 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent).catch((err) => console.error(err));

View File

@@ -0,0 +1 @@
/* You can add global styles to this file, and also import other style files */