MALINKA MALINKA - 1 month ago 19
TypeScript Question

manual inject into the constructor got error signature

I am trying to implement a logger to 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);
}
}


I don't understand at these two lines:

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


SqliteLoggerImpl constructor needs an IRepository, and I already give it.
LoggerServiceImpl constructor needs an ILogger, and I already give it.

Why still I see this, "[ts] Supplied parameters do not match any signature of call target" ?

Answer

TypeScript isn't like other languages where the constructor is the name of the class. You need to use the keyword constructor. What you have in all your implementations is just a method in the class that is the same name of the class. This method is not what is called when using new. It is the constructor. And every class has a default no-arg constructor when we don't define one. So when you try to do new Something(someArg), this will fail, as the default no-arg constructor doesn't take arguments. So just change all your "supposed constructors" to constructors