typescript-cheatsheet
typescript-cheatsheet copied to clipboard
Incorrect Code Snippet [Interface Example]
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