1

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

tksilicon
  • 3,276
  • 3
  • 24
  • 36
  • 2
    Well `userModel` is an object, and `ourFunctionModel` is expecting a constructor. `ourFunctionModel(UserModel)` would work here. – Keith May 21 '20 at 09:11
  • 1
    You are completely right because what was needed in the factory was a prototype of target. Please move comment to answer let me accept. See edit. – tksilicon May 21 '20 at 09:22

0 Answers0