我不明白 TS 错误。
这是一个代码示例:
interface initParams {
withoutAuth?: any;
scripts?: any; // reference to a file that produces scripts
setProxy: any;
}
class LoaderService {
bar1: any;
constructor() {
}
}
class ServerBaseService<T extends LoaderService> {
constructor(
private readonly _createClass: { new(): T },
private readonly isKube: boolean,
) {
}
}
class HttpLoaderService extends LoaderService {
constructor({ withoutAuth, scripts, setProxy }: initParams) {
super()
}
}
class ServerHTTPService<T extends HttpLoaderService> extends ServerBaseService<T> {
constructor(
private readonly _createClasss: new () => T, //{ new(): T }
private readonly withoutAuth: boolean,
private readonly setProxy: boolean,
private readonly isKubee: boolean
) {
super(_createClasss, isKubee) //_createClasss, // будет вызван конструктор ServerBaseService
}
}
class AuthLoaderService extends HttpLoaderService {
}
class AuthenticationServerService extends ServerHTTPService<AuthLoaderService> {
constructor({ withoutAuth, setProxy, isKube }: { withoutAuth: boolean, setProxy: boolean, isKube: boolean }) {
super(AuthLoaderService,withoutAuth,setProxy,isKube)
}
}
为什么这里会出现以下错误?
Argument of type 'typeof AuthLoaderService' is not assignable to parameter of type 'new () => AuthLoaderService'.
Types of construct signatures are incompatible.
Type 'new ({ withoutAuth, scripts, setProxy }: initParams) => AuthLoaderService' is not assignable to type 'new () => AuthLoaderService'
在
AuthenticationServerService
中,调用super()
时,引用的是ServerHTTPService
构造函数。
但错误消息引用了 HttpLoaderService
构造函数签名。
为什么?有人能解释一下这个错误吗?
ServerHTTPService
和ServerBaseService
构造函数中的第一个参数是:
_createClasss: new () => T
所以它必须是一个不带参数的构造函数。这与从
AuthLoaderService
类继承的 HttpLoaderService
类的构造函数不兼容:
constructor({ withoutAuth, scripts, setProxy }: initParams)
您的选择:
ServerHTTPService
和 ServerBaseService
中的构造函数参数类型以包含 initParams
参数:constructor(
private readonly _createClass: { new(params: initParams): T },
...
constructor(
private readonly _createClass: { new(...args: any[]): T },
...
initParams
是可选的,那么您必须将它们定义为可选interface initParams {
withoutAuth?: any;
scripts?: any;
setProxy?: any;
}
class HttpLoaderService extends LoaderService {
constructor({ withoutAuth, scripts, setProxy }: initParams = {}) {
super()
}
}