Having trouble implementing keyboard functionality into my snake game project using typescript. The code is throwing errors on lines 42 and 43, specifically:
- When hovering over the "window" keyword, the error reads:
Parsing error: ';' expected.eslint Unexpected keyword or identifier.ts(1434)
- Hovering over ".addEventListener" shows the error:
Function implementation is missing or not immediately following the declaration.ts(2391)
3)When hovering over the "window" keyword in the second line, there is another error:
Duplicate identifier 'window'.ts(2300)
interface keyUtil{
value:string,
isDown:boolean,
isUp:boolean,
press:undefined|any,
release:undefined|any
}
export class keyboard implements keyUtil{
// privatethis:object = {};
constructor(public value:string, public isDown:boolean, public isUp:boolean, public press:any, public release:any){
this.value = value;
this.isDown = false;
this.isUp = true;
this.press = undefined;
this.release = undefined;
}
downHandler = (event: KeyboardEvent) => {
if (event.key === this.value) {
if (this.isUp && this.press) this.press();
this.isDown = true;
this.isUp = false;
event.preventDefault();
}
};
upHandler = (event: KeyboardEvent) => {
if (event.key === this.value) {
if (this.isDown && this.release) this.release();
this.isDown = false;
this.isUp = true;
event.preventDefault();
}
};
const downListener = this.downHandler.bind(this);
const upListener = this.upHandler.bind(this);
//Error on following two lines:
window.addEventListener(type: "keydown", downListener:any):void;
window.addEventListener(type: "keyup", upListener:any):void;
unsubscribe = () => {
window.removeEventListener("keydown", this.downListener);
window.removeEventListener("keyup", this.upListener);
};
}
Solutions I tried were to modify the tsconfig file's noImplicitAny property to false. As I had coded the function in js, I was trying to convert the file to ts. Here is the js code:
function keyboard(value) {
let key = {};
key.value = value;
key.isDown = false;
key.isUp = true;
key.press = undefined;
key.release = undefined;
key.downHandler = event => {
if (event.key === key.value) {
if (key.isUp && key.press) key.press();
key.isDown = true;
key.isUp = false;
event.preventDefault();
}
};
key.upHandler = event => {
if (event.key === key.value) {
if (key.isDown && key.release) key.release();
key.isDown = false;
key.isUp = true;
event.preventDefault();
}
};
const downListener = key.downHandler.bind(key);
const upListener = key.upHandler.bind(key);
window.addEventListener(
"keydown", downListener, false
);
window.addEventListener(
"keyup", upListener, false
);
key.unsubscribe = () => {
window.removeEventListener("keydown", downListener);
window.removeEventListener("keyup", upListener);
};
return key;
}