The compiler detected an unanticipated keyword or identifier at line 1434. The function implementation is either absent or not placed directly after the declaration at line 239

Having trouble implementing keyboard functionality into my snake game project using typescript. The code is throwing errors on lines 42 and 43, specifically:

  1. When hovering over the "window" keyword, the error reads:

Parsing error: ';' expected.eslint Unexpected keyword or identifier.ts(1434)

  1. 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;
}

Answer №1

It appears that you have mixed up function definitions with function calls.

Here is an example of a (incorrect) function definition:

//Error on the following two lines:  
    window.addEventListener(type: "keydown", downListener:any):void;
    window.addEventListener(type: "keyup", upListener:any):void;

These should actually be placed in the class constructor as function calls:

constructor() {
    window.addEventListener("keydown", downListener);
    window.addEventListener("keyup", upListener);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: Unable to locate file 'socket.io-client/dist/socket.io.min.js'

Attempting to set up the Spika backend (node application), I ran into an issue while trying to start the server in standalone mode with the command: $ node src/server/main.js The error that popped up was: Error: Cannot find module 'socket.io-clien ...

What is the best way to eliminate leading and trailing spaces from a text input?

I'm currently working on troubleshooting a bug in an AngularJS application that involves multiple forms for submitting data. One of the issues I encountered is that every text box in the forms is allowing and saving leading and trailing white spaces ...

Regular expression that detects a phone number which does not consist of a repetition of the same digit throughout

Looking for a regex pattern to match phone numbers that do not consist of the same number repeated throughout every part. Specifically, I need it to target 10-digit phone numbers in the format (123)123-1234. I have tried using this pattern, but it's ...

Differences between RxJs Observable<string> and Observable<string[]>

I'm struggling to grasp the concept of RxJS Observables, even though I have utilized the observable pattern in various scenarios in my life. Below is a snippet of code that showcases my confusion: const observable: Observable<Response> = cr ...

Confirm button title by verifying part of the label that contains a space

I'm facing an issue with clicking a button using the following code: await page.getByRole('button', { name: '3 Employees' }).click(); The problem is that the button's name fluctuates based on the number of employees, causing ...

Enhancing w3-import-html with JavaScript

<div id="import" includeHTML="page.html"></div> function getInclude() { var x = document.getElementById("import").includeHTML; //returns 'undefined' alert(x); } function modInclude() { document.getElementById("import") ...

Make sure a specific piece of code gets evaluated in a timely manner

To ensure the default timezone is set for all moment calls in the app's lifetime, I initially placed the setter in the entry point file. However, it turns out that this file is not the first to be evaluated. An issue arose with one of my reducers wher ...

How can I dynamically add a named property to a class during runtime and ensure that TypeScript recognizes it?

Within my coding project, I have implemented a decorator that alters a class by adding additional methods to it, specifically in the class A. However, when utilizing an instance of this class, the added methods do not show up in the autocomplete feature. A ...

Comparing global variables in ng-switch: Best practices

I'm currently utilizing the AngularJS $rootScope object to expose some global constants that should be accessible to both controllers and views: var app = angular.module('myApp', []); app.run(function ($rootScope) { $rootScope.myConsta ...

Change a space-separated string containing coordinates into an array of JavaScript objects

Here is a string separated by spaces: const coordinates = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604" Now, we want to convert it into an array of objects: const coordinatesArray = [ { lat: 42.44492, lng: 75.637764 }, { lat: 42.4455 ...

Adjusting Image Width with jQuery on Hover

I am trying to create a hover effect for two images placed side by side. When the user hovers over one of the images, it should expand. HTML: <a href="#"><div id="skinny"></div></a> <a href="#"><div id="room9"></div ...

What is the best way to transfer a variable from an @Input property to a service within an Angular2 component?

I'm tackling what seems like a simple task, but I'm struggling to figure it out. My issue is this: How can I successfully pass a variable from @Input to a service in an Angular2 component? (Code has been simplified) This is my current component ...

I attempted to use ng add @angular/pwa, but encountered an error code that is baffling to me. Are there any steps I can take to resolve this issue?

npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While trying to find a solution: [email protected] npm ERR! Found: @angular/[email protected] npm ERR! in node_modules/@angular/common npm ERR! @angular/common@"^14.2.3" ...

Trouble arises when emitting events in Vue using eventHub

In the development of my component, there arises a need to emit an event at a specific point in its lifecycle. This emitted event is intended to be listened to by another sibling component. To facilitate this communication, I am utilizing an event hub. H ...

Allow access to the configuration file for a JavaScript file located in the public directory of an Express application

I have a specific question regarding the folder structure of my Express app. app │ │ └───config │ │ config.js │ │ └───public │ │ │ └───javascripts │ │ exportable.js │ ...

What is the method for transforming latitude and longitude coordinates into a physical address for a website?

I'm working with an API that provides latitude and longitude coordinates, and I need to retrieve the address information (city, area, etc.) based on these values. For example, there is a website like where if we enter the IP address of a location, i ...

Filtering a string that contains commas using another string that also contains commas

I need help with removing elements from one comma-separated string based on another. String 1: 6,2 String 2: 1,2,4,5,6,7,9,12,13 Is there a function or method that can accomplish this task for me? ...

jQuery Issue: Submission Count Doubling with Each POST Request

My current issue involves using jQuery to send data to a PHP file, but I've noticed that each time I submit the form, the data gets duplicated. Initially, it posts once when I press the submit button. However, upon returning to update the form and sub ...

When attempting to utilize VueJs v-bind:type on an input element, it appears to be ineffective when the type property name is

Code: <!DOCTYPE html> <html> <head> <title>Creating a Vue app</title> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3046455570021e061e0100">[ ...

Utilizing numerous copies of a single plugin

I recently integrated a plugin called flip-carousel.js into my website and here is an example of how it looks on the site. Check out the sample implementation Now, I encountered an issue when trying to use multiple instances of the same plugin. When init ...