typescript-cheatsheet icon indicating copy to clipboard operation
typescript-cheatsheet copied to clipboard

Incorrect Code Snippet [Interface Example]

Open uzair004 opened this issue 6 months ago • 0 comments

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

uzair004 avatar Aug 16 '24 20:08 uzair004