I have this code snippet in typescript playground:
interface IFoo {
new?():string;
}
class Foo implements IFoo {
new() {
return 'sss';
}
}
I have to put "?" in the interface method new, otherwise it will show compile error. I cannot figure out why.
Update: the original question is not a good way of using new, so I post a more realistic and practical way of using the above mentioned new():
interface IUser {
id: number;
name: string;
}
interface UserConstructable {
new (id: number, name: string, ...keys: any[]): IUser;
}
class User implements IUser {
constructor(public id: number, public name: string) {
}
}
class Employee implements IUser {
constructor(public id: number, public name: string,
private manager: string) {
}
}
class UserFactory {
private static _idx: number = 0;
static makeUser(n: UserConstructable): IUser {
let newId = UserFactory._idx++;
return new n(newId, 'user-' + newId, 'manager-' + newId);
}
}
console.log(UserFactory.makeUser(User));
console.log(UserFactory.makeUser(User));
console.log(UserFactory.makeUser(Employee));