I want to create a function that can be invoked with the new keyword. However, none of my implementation works and Typescript keeps showing me errors.
Below is my code. You can see it on the Typescript Playground too
type Account = {
username: string
password: string
}
type AccountConstructor = {
new (username: string, password: string): Account
(username: string, password: string): Account
}
// const Account: AccountConstructor = function (username: string, password: string) {
// return {username, password}
// }
// Type '(username: string, password: string) => { username: string; password: string; }' is not assignable to type 'AccountConstructor'.
// Type '(username: string, password: string) => { username: string; password: string; }' provides no match for the signature 'new (username: string, password: string): Account'.
const Account: AccountConstructor = function(username: string, password: string) {
return {
username,
password
}
}
// Type 'typeof Account' is not assignable to type 'AccountConstructor'.
// Type 'typeof Account' provides no match for the signature '(username: string, password: string): Account'.
const Account: AccountConstructor = class {
constructor(public username: string, public password: string) {}
}
new Account('username', 'password')
How to implement the Construct Signature correctly that the function could be invoked using the new keyword?
class Account { ... }?AccountClassclass is created just to test if the normal class works fine. It does not relate to the question. I have updated the code, so we can focus on the errors thrown by the Construct Signature, which is theAccountConstructortypeclass Account { ... }is okay but I want to use thenewkeyword to invoke a function just like I can do with JavaScript. I discovered construct signature, but don't know how to use it. The official doc doesn't show how to implement it too.classsyntax.