Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between two code in typescript?

I was just starting typescript and got stuck on this issue.

I have two codes, in first code there is an object name and in another code (same as first code) the variable name is changed to user. Now the problem is first code is creating error but first is working fine.

First Code (Producing Error)

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);

Second Code (Working fine)

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);

Please help me to understand this.

Edited

This is what I am getting while compiling first script
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'.
like image 298
Bug Hunter Avatar asked May 25 '26 09:05

Bug Hunter


1 Answers

It's because name is a global variable defined in lib.d.ts (Window.name):

declare var name: string;

The reason you're getting this error is because your code is also in the global scope. That's why using a different variable name works.

like image 113
David Sherret Avatar answered May 28 '26 00:05

David Sherret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!