@@ -28,28 +28,70 @@ interface Boat {
2828
2929type Vehicle = Bicycle | Car | Moto | Bus | Boat ;
3030
31+ export function createVehicle ( type : 'bicycle' ) : Bicycle ;
32+ export function createVehicle ( type : 'moto' , fuel : Fuel ) : Moto ;
33+ export function createVehicle ( type : 'car' , fuel : Fuel ) : Car ;
34+ export function createVehicle ( type : 'boat' , capacity : number ) : Boat ;
35+ export function createVehicle (
36+ type : 'bus' ,
37+ capacity : number ,
38+ isPublicTransport : boolean ,
39+ ) : Bus ;
3140export 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 || typeof fuelOrCapacity === 'number' ) {
51+ throw new Error ( `fuel property is missing for type ${ type } ` ) ;
52+ }
53+
54+ return { fuel : fuelOrCapacity , type } ;
4455 case 'boat' :
45- if ( ! capacity )
56+ if ( ! fuelOrCapacity || typeof fuelOrCapacity === 'string' ) {
4657 throw new Error ( `capacity property is missing for type boat` ) ;
47- return { capacity, type } ;
58+ }
59+
60+ return { capacity : fuelOrCapacity , type } ;
4861 case 'bus' :
49- if ( ! capacity )
62+ if ( ! fuelOrCapacity || typeof fuelOrCapacity === 'string' ) {
5063 throw new Error ( `capacity property is missing for type bus` ) ;
51- if ( ! isPublicTransport )
64+ }
65+ if ( isPublicTransport === undefined ) {
5266 throw new Error ( `isPublicTransport property is missing for type bus` ) ;
53- return { capacity, isPublicTransport, type } ;
67+ }
68+
69+ return { capacity : fuelOrCapacity , isPublicTransport, type } ;
5470 }
5571}
72+
73+ // export function createVehicle(
74+ // type: VehicleType,
75+ // fuel?: Fuel,
76+ // capacity?: number,
77+ // isPublicTransport?: boolean,
78+ // ): Vehicle {
79+ // switch (type) {
80+ // case 'bicycle':
81+ // return { type };
82+ // case 'car':
83+ // case 'moto':
84+ // if (!fuel) throw new Error(`fuel property is missing for type ${type}`);
85+ // return { fuel, type };
86+ // case 'boat':
87+ // if (!capacity)
88+ // throw new Error(`capacity property is missing for type boat`);
89+ // return { capacity, type };
90+ // case 'bus':
91+ // if (!capacity)
92+ // throw new Error(`capacity property is missing for type bus`);
93+ // if (!isPublicTransport)
94+ // throw new Error(`isPublicTransport property is missing for type bus`);
95+ // return { capacity, isPublicTransport, type };
96+ // }
97+ // }
0 commit comments