Primary Objective: My main focus is to grasp the concept of creating a Factory in Typescript, not just copying and pasting code. I am specifically struggling with understanding types and type inference. My goal is to have a "MyCloner" class that can generate multiple instances of an object that implements the IClonable interface, such as Truck or Motorcycle.
I envision being able to do something like this:
const vehicleCloner = new MyCloner();
const truck = new Truck({color: 'red', fuel: 'electric'});
And then use MyCloner to achieve the following:
var myTenElectricTrucks = vehicleCloner.cloneWithRandomColors(truck, 10);
First Area of Confusion (infer and new): I've been studying various tutorials, but one particular section has me puzzled:
type ExtractInstanceType<T> = T extends new () => infer R ? R : never;
The syntax here is throwing me off. It seems we are defining a type with a generic called T, which seems to extend the "new" function keyword. How are R, T, and 'new' connected? I'm also unsure about the purpose of the => operator and what infer does in Typescript.
If you're interested, you can find more information on ExtractInstanceType in this tutorial.
I acknowledge that keeping all trucks electric might be an additional feature not commonly seen in the Factory pattern, but grasping infer and ExtractInstanceType fundamentals should pave the way for achieving this ultimate objective.
Second Area of Confusion (type declarations & literals):
Another line from the same tutorial is causing confusion:
type userTypes = typeof userMap[Keys]; //typeof Developer | typeof Manager
To me, it appears that Keys isn't just a single key. Normally in JavaScript, I would expect it to be a string retrieving a single value from a dictionary. However, Keys seems to represent multiple types as a type literal, which is then utilized as a single key somehow?
You can refer to Keys below:
type Keys = keyof typeof userMap; // 'dev' | 'manager'