I am currently generating client models (Entities) along with their corresponding Primary Keys.
My goal is to create a method signature where, based on the Entity provided, the second parameter should be its Primary Key only.
The specific use of types and classes mentioned in the code snippet below may not be mandatory and could potentially be replaced by interfaces or constants for mapping purposes.
This is what I have attempted so far:
export type ClassType<T> = new (...args: any[]) => T
export class CustomerPk {
customerId: number;
}
export class VendorPk {
vendorId: number;
}
export class Customer implements CustomerPk {
customerId: number;
name: string;
}
export class Vendor implements VendorPk{
vendorId: number;
name: string;
}
export type EntityType = Customer | Vendor;
export type EntityPk = CustomerPk | VendorPk;
export type entityToPkMap = {
Customer: CustomerPk, Vendor: VendorPk
}
To use it as follows:
constructor() {
const myCust = this.getData(Customer, new CustomerPk());
const myVend = this.getData(Vendor, new CustomerPk()); // Intended to provide compile-time verification.
}
public getData<T extends EntityType, K>(entity: ClassType<T>, primaryKey: K): T {
throw new Error('Not Implemented');
}
I have experimented with different variations but have yet to achieve the desired outcome:
public getData<T extends EntityType, K extends entityToPkMap[T]>(entity: ClassType<T>, primaryKey: K): T
This results in an error stating "Type 'T' cannot be used to index type 'entityToPkMap'."