任何人都可以解释这个 TypeScript 错误吗?

问题描述 投票:0回答:1

我不明白 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)

    }

}

TS游乐场

为什么这里会出现以下错误?

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
构造函数签名。 为什么?有人能解释一下这个错误吗?

javascript typescript
1个回答
0
投票

ServerHTTPService
ServerBaseService
构造函数中的第一个参数是:

_createClasss: new () => T

所以它必须是一个不带参数的构造函数。这与从

AuthLoaderService
类继承的
HttpLoaderService
类的构造函数不兼容:

constructor({ withoutAuth, scripts, setProxy }: initParams)

您的选择:

  1. 更改
    ServerHTTPService
    ServerBaseService
    中的构造函数参数类型以包含
    initParams
    参数:
constructor(
    private readonly _createClass: { new(params: initParams): T },
    ...
  1. 如果由于某种原因参数并不重要(取决于您实际想要做什么),您可以忽略它们:
constructor(
    private readonly _createClass: { new(...args: any[]): T },
    ...
  1. 如果
    initParams
    是可选的,那么您必须将它们定义为可选
interface initParams {
    withoutAuth?: any;
    scripts?: any;
    setProxy?: any;
}
class HttpLoaderService extends LoaderService {
    constructor({ withoutAuth, scripts, setProxy }: initParams = {}) {
        super()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.