When I first started learning TypeScript, I encountered an issue that has me stuck.
In my code, there are two versions: in the first version, there is an object called name
, and in the second version (which is essentially the same), the variable name has been changed to user
. The problem is that the first version is throwing an error, while the second version is running smoothly.
Error-producing First Code
interface Person {
firstName : string;
lastName : string;
}
function greeter(person: Person) {
return "Hello " + person.firstName + " " + person.lastName;
}
var name = {firstName: "Girdhari", lastName: "Agrawal"};
document.body.innerHTML = greeter(name);
Working Fine Second Code
interface Person {
firstName : string;
lastName : string;
}
function greeter(person: Person) {
return "Hello " + person.firstName + " " + person.lastName;
}
var user = {firstName: "Girdhari", lastName: "Agrawal"};
document.body.innerHTML = greeter(user);
I'm struggling to understand this difference between the two versions. Any help would be appreciated.
Edit:
Upon compiling the first script, I received the following errors:
greeter.ts(10,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'name' must be of type 'string', but here has type '{ firstname: string; lastName: string; }'.
greeter.ts(13,35): error TS2345: Argument of type 'string' is not assignable to parameter of type 'Person'.