手动注入构造函数得到错误签名

manual inject into the constructor got error signature

我正在尝试为 sqlite 实现一个记录器。

ilogger.ts

export interface ILogger {
    write (log: Log): any;
}

ilogger.service.ts

export interface ILoggerService {
    info(log: Log): any;
    error(log: Log): any;
}

irepository.ts

export interface IRepository<T> {
    find(key: number): any;
    insert(data: T): any;
    remove(key: number): any;
    fetch(count: number, skip: number): any;
}

sqlite.logger.impl.ts

export class SqliteLoggerImpl implements ILogger {

    sqliteRepo: IRepository<Log>;

    SqliteLoggerImpl(sqliteRepo: IRepository<Log>) {
        this.sqliteRepo = sqliteRepo;
    }

    write(log: Log): any {
        return this.sqliteRepo.insert(log);
    }
}

logger.service.impl.ts

export class LoggerServiceImpl implements ILoggerService {
    logger: ILogger;

    LoggerServiceImpl(logger: ILogger) {
        this.logger = logger;
    }

    info(log: Log): any {
        log.severity = 0;
        return this.logger.write(log);
    }

    error(log: Log): any {
        log.severity = 1;
        return this.logger.write(log);
    }
}

app.component.ts

@Component({
    selector: "my-app",
    templateUrl: "app.component.html"
})
export class AppComponent {
    logs: Array<Log>;
    loggerService: ILoggerService;

    constructor() {
        let repo: IRepository<Log> = new SqliteRepositoryImpl();

        // [ts] Supplied parameters do not match any signature of call target
        let logger: ILogger = new SqliteLoggerImpl(repo);
        this.loggerService = new LoggerServiceImpl(logger);
    }
}

这两行我没看懂:

let logger: ILogger = new SqliteLoggerImpl(repo);
this.loggerService = new LoggerServiceImpl(logger);

SqliteLoggerImpl 构造函数需要一个 IRepository,我已经给了它。 LoggerServiceImpl 构造函数需要一个 ILogger,我已经给了它。

为什么我仍然看到这个,“[ts] 提供的参数与调用目标的任何签名都不匹配”?

TypeScript 不像其他语言那样构造函数是 class 的名称。您需要使用关键字 constructor。您在所有实现中所拥有的只是 class 中的一个方法,它与 class 同名。此方法不是使用new时调用的方法。就是constructor。当我们没有定义时,每个 class 都有一个默认的无参数构造函数。因此,当您尝试执行 new Something(someArg) 时,这将失败,因为默认的无参数构造函数不接受参数。所以只需将所有 "supposed constructors" 更改为 constructors