dopatraman
dopatraman

Reputation: 13908

Error when instantiating class: Supplied parameters do not match any signature of call target

I have a class here:

export class MyClass {
    public name:string;
    public addr:string;

    constructor() {}
}

And I import it here:

import { MyClass } from './MyClass';

// and use it here:

class MyUser {
    private _prop : MyClass[];

    constructor() {
        this._prop = [
            new MyClass({name: 'Hello', addr: 'World'}) //<--- this is where the error appears
        ]
    }
}

When I do this I get a linting error:

Supplied parameters do not match any signature of call target

Why can't I instantiate my class?

Upvotes: 1

Views: 471

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

You haven't had mention any parameter in your MyClass constructor. You have to put parameter in constructor so that you can set value while instantiating this class. You could move MyClass properties to constructor parameter to make it shortened syntax like below.

export class MyClass {
    //by having `public` on constructor shortened the syntax.
    constructor(public name: string, public addr:string) {

    }
}   

constructor() {
    this._prop = [
        new MyClass('Hello', 'World')
    ]
}

Playground Demo

Upvotes: 1

Thierry Templier
Thierry Templier

Reputation: 202256

You should have the following for your constructor. In your case, you defined no parameters:

constructor(param:{name:string, addr:string}) {
  this.name = param.name;
  this.addr = param.addr;
}

Another option would be to define your class properties at the level of your constructor:

constructor(public name:string, public addr:string) {
  // No need for this:
  // this.name = name;
  // this.addr = addr;
}

You can now pass parameter to your constructor and they'll use to initialize your instance properties:

constructor() {
  this._prop = [
    new MyClass('Hello', 'World'})
  ];
}

Upvotes: 1

Related Questions