1

I'm attempting to define what arguments must be passed to a function in React with Typescript:

type IncrementDecrementFunctionArgs = {
  id: number;
  amount: string;
  foo: string;
};

export const dummyProps = {
  increment: function({ id, amount }: IncrementDecrementFunctionArgs) {
    console.log("increment ", id, " by amount: ", amount);
  }
}

Props are spread into component:

<Component {...dummyProps} />  

Component calls function:

  const handleClick = (val: incrementDecrement) => {
    if (val === incrementDecrement.increment) {
      increment({ id, amount });
    } else {
      decrement({ id, amount });
    }
  };

I can't work out why this isn't erroring. foo does not exist. id is a string and amount is a number.

0

1 Answer 1

1

Because the function you've implemented can, in-fact, accept foo as a property of the object parameter.

The following is valid with your function:

props.increment({id: 1, amount: 2, foo: 3}); // no runtime errors.

Ignored properties are allowed in TypeScript, because it is valid to call with parameters that are being ignored by the function.

Sign up to request clarification or add additional context in comments.

2 Comments

Hey! I know this is can be rude, but I been looking for someone to help me with writing better answers. Because I have been trying to find you in chat rooms for over two weeks, I just wanted to ask you what improvements I can do in this answer: stackoverflow.com/questions/57507019/…, or if it is great to tell me. If you think this comment should be removed I would happily remove it. Thanks for your attention :)
Please check it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.