Please, I have read this answer and this one.
However, consider the following use case:
//Connection Type
interface Connection {
}
// Model class
class BaseModel {
created_at?: Date;
updated_at?: Date;
constructor(public connection?: Connection) {}
}
// Class that implements BaseModel
class UserModel extends BaseModel {
constructor() {super()}
}
// A factory function which takes type T that must extend BaseModel
function Model<T extends BaseModel>(name: string) {
return (target: { new (): T }) => {
console.log(target.prototype);
};
}
//type of target in the anonymous function returned by Model function factory
interface OurTarget {
new(): UserModel;
}
// this does not give error
var ourFunctionModel = Model("user");
// this does not give error
var userModel = new UserModel();
// TS2345 not assignable error
ourFunctionModel(userModel);
//Correct Usage provided in comments by [@keith][3]
const ourFunctionModel = Model("user")(UserModel);
In the anonymous function of Model which takes a target which of type OurTarget. OurTarget defines a new() which for UserModel which extends BaseModel. Why is the last line of code throwing error, it was given the right type?
Here is the code on TypeScript playground