Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect Code Snippet [Interface Example] #44

Open
uzair004 opened this issue Aug 16, 2024 · 0 comments
Open

Incorrect Code Snippet [Interface Example] #44

uzair004 opened this issue Aug 16, 2024 · 0 comments

Comments

@uzair004
Copy link

The following interface section contain a code snippet as follows.

  interface NamedPerson {
    firstName: string;
    age?: number;
    [propName: string]: any;
    greet(lastName: string): void;
  }

  class Person implements NamedPerson {
    constructor(public firstName: string, public lastName: string) {}
    greet(lastName: string) {
      console.log(`Hi, I am ${this.firstName} ${lastName}!`);
    }
  }

  const myPerson = new Person('Robert', 'Molina');
  greet(myPerson); // Prints: "Hi, I am Robert Moina"

Description

The provided TypeScript code snippet results in a compilation error due to the incorrect invocation of a greet function, which is not defined. The code intends to greet a person using a method in the Person class, but incorrectly calls a non-existent greet function instead of the method.

Problem

The following error occurs because the code attempts to call a greet function with a Person instance as an argument:

Error

greet(myPerson); // Error: 'greet' function is not defined

Possible Solutions

1. Directly call the greet method on the Person instance

myPerson.greet('Molina'); // Correct usage

or
2. Define a standalone greet function if a separate function is needed

function greet(person: NamedPerson) {
  person.greet(person.lastName);
}
greet(myPerson); // Correct usage with the standalone function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant