I'm having problems understanding how to correctly type a constructor function in TS. I'm aware that a common answer would be to use a class, but I'm currently exploring TS features. In my tsconfig.json I have noImplicitAny: true.
My constructor function looks like this in JS:
function User(username) {
this.username = username
}
User.prototype.age = 57
My first attempt to type the functions relied on the TS docs that explain how to define call signatures:
interface IUser {
username: string;
age: number;
}
type UserConstructor = {
(username: string): void;
new (username: string): IUser;
}
const User: UserConstructor = function(username: string) {
this.username = username
}
User.prototype.age = 57
The compiler complains since the value of this is unknown and the call signatures don't seem to match.
After doing some research, I was able to come up with a version that works but I don't really like it:
interface ICUser {
username: string;
age: number;
}
function ConstructedUser(this:ICUser, username: string) {
this.username = username;
}
ConstructedUser.prototype.dateOfBirth = "Freb"
Here's what I don't like about solution nr. 2:
- I'm not sure I completely understand the explicit passing of this since there aren't any official docs on this.
- The typing is very verbose and does not separate between properties on the instance and prototype chain.
I wasn't able to find good resources on how to type constructor functions and hoped someone might be able to help.
classsyntax? Typescript can compile it to a constructor function if you set the target language level appropriately.