Machtyn
Machtyn

Reputation: 3272

Supplied parameter error when using a mixin in typescript

I'm trying to learn Typescript and was playing with the mixin idea. I have the following code, which is silly, but it's practice. Also, it works when I run it. But the line 42, myInput.sendKeys(name);, states "Supplied parameters do not match signature of target." But I'm not sure what I need to change to fix it.

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            derivedCtor.prototype[name] = baseCtor.prototype[name];
        });
    });
}

class SendKeys {
    inputEl;

    sendKeys(data: string) {
        this.inputEl.value = data;
    }
}

class InputClass implements SendKeys {
    inputEl: HTMLInputElement;

    constructor() {
    }

    sendKeys: () => void;

    createInput(name: string) {
        this.inputEl = document.createElement('input');
        this.inputEl.type = 'text';
        this.inputEl.setAttribute('id', name);
        document.body.appendChild(this.inputEl);
        document.body.appendChild(document.createElement('br'));
    }
}
applyMixins(InputClass, [SendKeys])


let myInput = new InputClass();

let nameArr = ["frank", "Joe", "Laryy"];

for (let name of nameArr) {
    myInput.createInput(name);
    myInput.sendKeys(name);
}

See the code in action here

Upvotes: 0

Views: 60

Answers (2)

Bruno Grieder
Bruno Grieder

Reputation: 29814

TL;DR; fix the signature of sendKeys in InputClass to:

 sendKeys: (data: string) => void;

The applyMixin method is executed at runtime.

At compile time, there is no way that the Typescript compiler knows that your you are going to mix class SenKeys into class InputClass and by doing so change the signature of the sendKeys method from a parameter less, to a single parameter method.

Upvotes: 1

Nitzan Tomer
Nitzan Tomer

Reputation: 164139

You are implementing SendKeys incorrectly, it should be:

sendKeys: (data: string) => void;

Like this:

class InputClass implements SendKeys {
    inputEl: HTMLInputElement;

    constructor() {}

    sendKeys: (data: string) => void;

    createInput(name: string) {
        this.inputEl = document.createElement('input');
        this.inputEl.type = 'text';
        this.inputEl.setAttribute('id', name);
        document.body.appendChild(this.inputEl);
        document.body.appendChild(document.createElement('br'));
    }
}

(code in playground)

And then the error goes away.

Upvotes: 1

Related Questions