Machtyn Machtyn - 1 month ago 6
TypeScript Question

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

Answer

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.