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?