I have come across an issue with my TypeScript class that inherits another one. I am trying to create a factory class that can generate objects of either type based on simple logic, but it seems to be malfunctioning.
Here is the basic Customer class:
class Customer {
static member = true;
id:string;
static c_type = "Basic Customer";
makeTransaction():string {
var transaction_id = Math.random().toString(36).substr(2, 9);
console.log(this.constructor.toString().split ('(' || /s+/)[0].split (' ' || /s+/)[1]);
return transaction_id;
}
constructor(public name:string, public dob:string) {
this.id = Math.random().toString(36).substr(2, 9);
}
}
This class extends Customer to produce a VIP customer:
class VIPCustomer extends Customer{
vip_num:string;
vip_discount:number;
static c_type = "VIP Customer";
constructor(public name:string, public dob:string) {
super(name, dob);
this.vip_num = Math.random().toString(36).substr(2, 9);
}
}
The goal of the customer creator is to instantiate either a VIP or basic customer based on a string input, but it is currently not functioning properly.
class CustomerCreator {
static create(event: {name:string; dob: string}, type:string) {
console.log('Log type' + typeof type);
if (type === 'Basic') {
console.log('basic customer created');
return new Customer(event.name, event.dob);
}
if (type === 'VIP') {
console.log('VIP customer created');
return new VIPCustomer(event.name, event.dob);
}
}
}
console.log(Customer.c_type);
console.log(VIPCustomer.c_type);
const customer_1 = CustomerCreator.create({name:'Pii', dob:'03/19'}, 'VIP');
var customer_2 = CustomerCreator.create({name:'Matthew', dob:'12/70'}, 'Basic');
//accessing attributes
console.log(customer_1.name);
console.log(customer_1.id);
//console.log(customer_1.vip_num)
If you uncomment the last print statement, the code will not compile. Additionally, the printed statements suggest that for both customers 1 and 2, a basic customer is being created despite the intended string comparison. Where could I be making an error?