Home > Net >  typescript: Abstract class parameter in constructor of class
typescript: Abstract class parameter in constructor of class

Time:07-15

I want to pass a class as parameter to the constructor of a class.

interface IFileHandler {
  getFiles (): string[]
}

class FileHandler implements IFileHandler
{
  getFiles ()
  {
    return ['hello', 'world'];
  }
}

class XmlToJson
{
  private FileHandler: IFileHandler;

  constructor (FileHandler: IFileHandler)
  {
    this.FileHandler = new FileHandler();
  }
}

How do you use the proper types for this? I need FileHandler to depend on an abstract class.

I get this error

This expression is not constructable.
  Type 'IFileHandler' has no construct signatures.

EDIT: as requested

interface IFileHandler {
  getFiles (): string[]
}

class DerivedExampleFileHandler implements IFileHandler
{
  getFiles ()
  {
    return ['hello', 'world'];
  }
}

class XmlToJson
{
  private _fileHandler: IFileHandler;

  constructor (DerivedExampleFileHandler: IFileHandler)
  {
    this._fileHandler = new DerivedExampleFileHandler();
  }
}

still the following error:

This expression is not constructable.
  Type 'IFileHandler' has no construct signatures.

CodePudding user response:

It has nothing to do with naming, interfaces just don't have constructor signature, you can find more info here
So what you need to do is to define an interface with constructor signature:

interface IFileHandler {
  getFiles (): string[]
}

interface FileHandlerConstruct {
    new(): IFileHandler
}

class FileHandler implements IFileHandler
{
  getFiles ()
  {
    return ['hello', 'world'];
  }
}

class XmlToJson
{
  private FileHandler: IFileHandler;

  constructor (FileHandler: FileHandlerConstruct)
  {
    this.FileHandler = new FileHandler();
  }
}

const c = new XmlToJson(FileHandler)

A link to playground

CodePudding user response:

If you are going to employ dependency injection:

interface IFileHandler {
  getFiles (): string[]
}

class FileHandler implements IFileHandler
{
  getFiles ()
  {
    return ['hello', 'world'];
  }
}

class XmlToJson
{
  private FileHandler: IFileHandler;

  constructor (FileHandler: IFileHandler)
  {
    this.FileHandler = FileHandler;
  }

}

if you are going to employ object creation;

class XmlToJson
{
  private FileHandler: IFileHandler;

  constructor ()
  {
    this.FileHandler = new FileHandler();
  }

}

access the typescript link: here

Also, there's a quickway to implement this in typescript:

class XmlToJson
{
  constructor (private fileHandler : IFileHandler)
  {}
}

access to second solution: here

  • Related