What sets apart two pieces of TypeScript code from each other?

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'.

Answer №1

The issue stems from the fact that the variable name is a predefined global variable within the lib.d.ts file (Window.name):

declare var name: string;

Your code encounters an error due to being in the global scope as well. Renaming the variable will resolve this issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing data between Vue.js components effortlessly without relying on events

At the moment, I am utilizing Laravel Nova. It's worth noting that it operates using vue.js. I've created a personalized vue component which requires the ability to modify data inside another component. This specific component is located in the ...

JavaScript encounters difficulty in reading the text file

I am working on a project where I need to read a local text file located at /home/myname/Desktop/iot/public/sensordata.txt using JavaScript when a button is clicked on a web page. Below is the code snippet I have been using: <html> <head> ...

When trying to import SVGs using gatsby-plugin-react-svg, an error message stating "InvalidCharacterError: String contains an invalid character" is received

After realizing that my website's Largest Contentful Paint (LCP) might be affected by font-awesome svg icons, I decided to replace them. I extracted the svg code from my html and saved them as svg files. They appeared as images in my image editing sof ...

VueJS 3 Alert: The export component specified was not found in the specified path '@/components/...vue'

Currently, I am working with VueJS 3 applications that involve vue-router, vue, and core-js components. In my project, I have a file named Home.vue located in the views directory with the following structure: <template> <div class="wrapper& ...

Building nested components with Vue.js involves creating a complex routing structure within the architecture

Utilizing vue.js for my administration app, I aim to create a highly modular UI architecture. Therefore, I have structured and enclosed the Header, Body, Sidebar, and Main in single file components as illustrated below. Tree App - Header - dynamic cont ...

Is there an issue with the close button on the popup in Angular 6 not functioning

I'm having an issue with the close button on my popup box code. I am new to using Angular 6 and could use some assistance. Can anyone help me fix this problem? <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title"& ...

Here's a guide on passing a test case that involves using enzyme's shallow method with the contains function when testing a React component with an event

I'm struggling to pass a test that uses .contain when the react component contains an event handler. Here is an example: Foo.js const Foo = React.createClass({ render () { return ( <p onClick={() => {}}>I am not ...

Eliminate the star symbol - fixing the mishap with hasClass and removeClass in jQuery

Help needed! I'm trying to remove the asterisk class from the password field, but there seems to be a typo in my code. Can someone assist me with this issue? I've attempted to remove attributes, but that hasn't been successful either. I don& ...

Store a video file on your device's memory

Currently, I am storing simple strings in local storage. However, I am now facing the issue of wanting to save videos and images to local storage. Due to the limitations of localStorage supporting only strings, I am unsure of how to achieve this. If you h ...

Having trouble importing Bootstrap into Next.js? It seems like the issue may be related to the

I am currently facing an issue with importing bootstrap 5.3.2 (not react-bootstrap) into my NextJS 14.1.0 project that utilizes the new App Router. My goal is to strategically utilize individual Bootstrap components (not through data-attrs). I managed to ...

Leveraging HTML reporting in conjunction with the Mocha testing framework

Recently, I have been working on generating tests using NodeJS and Mocha. However, I am facing some challenges in putting the results into a browser. Although Mocha has support for this through the 'html' reporter and mocha init <dir>, both ...

Adjust the field type to supersede the type of the generic object

I'm looking to set the type of T (a generic) equal to the type of the listener field, so that I can have auto completion for "firstParameter" whether the listener is the default value or a custom one. Is this achievable? If not, is there another solut ...

Triggering Backbutton actions in Ionic 3Just a heads-up

I need to capture the back button event before it triggers. Once the listener is activated, the back signal has already been sent. This is my approach so far: document.addEventListener("backbutton", () => { console.log("[WARN] Back button pres ...

Error Encountered While Building AWS Amplify with Ionic 5 and Angular 10

Our team is currently facing a challenge at my company that we've been struggling to resolve, and I was hoping someone here could offer some assistance. We are using AWS Amplify in our Angular 10/Ionic 5 project, and encountering the following error: ...

Changing the value of one particular key within an object during a reduce operation will impact all other keys within the object as well

I'm completely lost here. It seems like there's a reference issue causing all data properties to be overwritten with the value of the last row. I need help figuring out how to iterate over a list of objects, using specific keys to assign data to ...

Requesting AJAX page yields a null $_GET parameter

Content loaded dynamically via AJAX methods. The base page is index.php, and profile.php is the page that gets loaded. The jQuery code snippet below has nothing to do with an HTML request: $('<a/>', {href: '?userID='+post[' ...

Troubleshooting focus loss in React input fields within a Datatable component implemented in a

I noticed an issue with my Datatable where the input field loses focus whenever I type a character and define the component inside another component. Surprisingly, when I directly place the component in the datatable, it works perfectly fine. I understand ...

Node receiving empty array as result after processing post request

My current task involves testing the post method on Postman. Strangely, every time I post the result it shows an empty array []. Upon further investigation by console logging on the node side, it also returns an empty array. CREATE TABLE users ( user_ ...

Create a graph that can retrieve and showcase information stored in a Rails database

Is there a way to incorporate a graph into a Ruby on Rails application that can access and show data from a database file (.rb)? If so, what would be the most optimal approach for achieving this? ...

Retrieving a portion of the response with Angular's HttpRequest

I am facing an issue with a request where I need to upload a file and receive a JSON response. The problem arises when trying to access a specific part of the response, namely body.path. Despite my efforts, I keep encountering an error stating that the pat ...