In the process of developing a repository module that includes generic methods, I have found that as long as each derived class has the `tableName` configured, the basic query for creating, finding, or deleting records remains consistent across all child classes.
Although I have made an attempt at this (outlined below), the TypeScript compiler is raising an error:
Type 'Car' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to 'Car'.
Consider the following example:
// Inside base-repo.ts
class BaseRepo {
static create<T>(columns, values): T {
// This is just a simplified example - the actual implementation is more robust
return db.execute(`INSERT INTO ${this.tableName} (${columns}) VALUES (${values})`)
}
}
// In car-repo.ts
interface Car {
id: number
make: string
model: string
}
class CarRepo extends BaseRepo {
static get tableName() {
return 'cars'
}
}
// In another file
// The goal is to automatically infer the type as `Car` based on configuration in `car-repo.ts`
const carRecord = CarRepo.create(..., ...)
// ----------------------------
// This approach does not work and results in the aforementioned error:
class CarRepo extends BaseRepo {
static create(columns, values): Car {
return BaseRepo.create<Car>(columns, values)
}
}
// This alternative solution works but is less than ideal
class BaseRepo {
static createRecord<T>(columns, values): T {}
}
class CarManufacturer extends BaseRepo {
static create(columns, values): Car {
return this.createRecord<Car>(columns, values)
}
}
It seems like the issue may lie in attempting to overwrite a parent method while the type signatures are not completely compatible.