My function executes smoothly when I pass a reference to an object, but it encounters an error when I include extra properties in the object and pass it as a value

In my coding project, there is a function called sayMyName that takes an argument of type User

When I pass a user as reference, everything works perfectly:

interface User{
  firstName:string;
  lastName:string;
}

function sayMyName(user:User){
  console.log(user.firstName + " " + user.lastName );
}

const user = {firstName: "john", lastName: "snow", age: 22}

sayMyName(user);

However, if I try to pass an object directly to sayMyName like this:

sayMyName({firstName: "john", lastName:"snow", age:22});

I encounter an error message:

Argument of type '{ firstName: string; lastName: string; age: number; }' is not assignable to parameter of type 'User'. Object literal may only specify known properties, and 'age' does not exist in type 'User'.

This issue has me puzzled - what exactly is causing the problem in my code?

Answer №2

@Vineet Desai is spot on, the issue here stems from the excess-property-checks.

Please consider my response as a supplementary addition to his explanation.

To work around this error, you can experiment with adding an additional generic for the user parameter:

interface User {
  firstName: string;
  lastName: string;
}

function sayMyName<T extends User>(user: T) {
  console.log(user.firstName + " " + user.lastName);
}

const user = { firstName: "john", lastName: "snow", age: 22 }

sayMyName(user); // works fine


sayMyName({ firstName: "john", lastName: "snow", age: 22 }); // also works

Try it out in Playground

Answer №3

If you're looking to utilize your function with an object that has specific keys, you can define it as shown below:

function printFullName({first, last}){
  console.log(first + " " + last);
}

This setup will function effectively for:

const currentUser: User = {first: "Jane", last: "Smith"}; 
const userRecord: Record<string, string> = {first: "Alice", last: "Johnson"};

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

Angular testing with Jasmine and TypeScript

I've been attempting to create some Angular Controller tests for my App using TypeScript for a few days now, but haven't had any success. Let me start by saying that this is my first time writing tests in Jasmine. My issue is that I'm having ...

The TypeScript type definition for reduce is used to aggregate values in

What is the best way to properly declare a type for this scenario? interface MediaQueryProps { [key: string]: number; } const size: MediaQueryProps = { small: 576, medium: 768, large: 992, extra: 1200 }; export default Object.keys(size).reduce ...

Altering the properties of a specified element within TestBed using the overrideComponent method

We are implementing TestBed.overrideComponent() to substitute a component with custom behavior. TestBed.overrideComponent(CoolComponent, { set: { template: '<div id="fake-component">i am the fake component</div>', sel ...

Utilizing next-redux-wrapper within the getServerSideProps function in Next.js allows for seamless

When trying to call an action function in getServerSideProps using TypeScript, I encountered some challenges. In JavaScript, it is straightforward: import { wrapper } from "Redux/store"; import { getVideo } from "Redux/Actions/videoAction&qu ...

Use an Angular array filter to return only values that match

In my dataset, each client is associated with a set of cases. I am looking to extract only those clients who have cases with the status "Open". Clients with cases marked as "Closed" should not be included in the filtered list. Currently, my filtering metho ...

Navigating through the directory to locate the referenced folder in a Types

Is there a way to declare a path to a referenced folder in order to have a more concise import statement using the @resources path? I am building from /server by running tsc -b app.ts The following long import statement works: import IEntity from &ap ...

What should be the output when ending the process using process.exit(1)?

I need to update my code by replacing throw new Error('Unknown command.') with a log statement and process.exit(1);. Here is the example code snippet: private getCommandByName = (name: string): ICommand => { try { // try to fetch ...

The declaration file for the 'vimeo' module was not located

My current setup includes typescript v^3.4.2, in an express app (^4.14.1), using node v11.3.0. During the build process for typescript, I encountered this error: Could not find a declaration file for module 'vimeo'. '/Users/me/Code/MyServe ...

The resolve.alias feature in webpack is not working properly for third-party modules

Currently, I am facing an issue trying to integrate npm's ng2-prism with angular2-seed. The problem arises when importing angular2/http, which has recently been moved under @angular. Even though I expected webpack's configuration aliases to hand ...

Can a generic type be utilized to instantiate an object?

In my code, I have a class named Entity as shown below: class Entity { constructor(readonly someValue: string) {} someFunction() {} } Now, I am trying to create a class that will handle these entities and be able to create instances of them. In or ...

Exploring nested arrays of subdocuments in a query

UPDATE: It is advised not to use the special characters &" in the query. They are meant for updates only. SOLUTION: Thanks to Gibbs correct: const result : any = await mongoose.model('Events').update( { _id: eventId, ...

Enhance your UI experience with a beautifully styled button using Material-

I was using a Material UI button with a purple background. <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', heig ...

The ThemeProvider from @emotion/react is not functioning properly

Operating System Information: Macbook Pro (M1 Pro) running Monterey 12.1 Library Version Information: React: 17.0.2, @emotion/react: 11.7.1, @emotion/styled: 11.6.0 Hello everyone, I am encountering an issue. When I use styled-components, everything wor ...

Tips for incorporating a reference into a styled component div in a React application using TypeScript

Looking to include a reference to a styled component div. Here is the code snippet: const DragAndDrop: React.FC<any> = props => { const divRef= React.createRef(); return ( <Zone ref={divRef}/> ); } Encountering thi ...

Type '{}' is lacking the subsequent attributes in type 'Record'

This is the code snippet I am working with: const data : Record<MediaType, Person[]> = {}; I encountered an error while initializing the 'data' object as shown above. The error message specifies that certain properties are missing from typ ...

Typescript issue: The function 'forEach' is not applicable for type 'string'

Whenever I try to use the forEach() method, an error appears in my terminal. [ts] Property 'forEach' does not exist on type 'string'. Although my application functions properly in the browser, I want to eliminate these errors from the ...

'Error: The type is missing the 'previous' property - Combining TypeScript with ReactJS'

I am quite new to using reactjs and ts. While I understand the error that is occurring, I am unsure of the best solution to fix it. Currently working with reactjs, I have created an: interface interface IPropertyTax { annul: { current: number; p ...

The async pipe is failing to function properly when used with the same observable

I'm facing an issue with the async pipe in my view as it's not loading any data dynamically. On my page, I need to change observable values multiple times such as reloading the page, loading more values, and updating news content based on differ ...

What is the best way to retrieve the previous URL in Angular after the current URL has been refreshed or changed

Imagine being on the current URL of http://localhost:4200/#/transactions/overview/5?tab=2 and then navigating to http://localhost:4200/#/deals/detail/ If I refresh the deals/detail page, I want to return to the previous URL which could be something like h ...

How to link observables in HTTP requests using Angular 5?

I'm currently developing an application using Angular 5, and I want to segregate raw http calls into their own services so that other services can modify the responses as needed. This involves having a component, component service, and component data ...