0

When calling functions with object arguments, extra keys are forbidden:

function foo({ key }) {}

foo({ key: 1, key2: 2 });

Argument of type '{ key: number; key2: number; }' is not assignable to parameter of type '{ key: any; }'.
  Object literal may only specify known properties, and 'key2' does not exist in type '{ key: any; }'

However, with React functional components, this error doesn't trigger:

function Foo({
  obj: { key },
}) {}

<Foo obj={{ key: 1, key2: 2 }} />

Is there a way to make this an error?

1

2 Answers 2

1

When trying to use Foo as a component like in your example I get the error 'Foo' cannot be used as a JSX component. Its return type 'void' is not a valid JSX element.ts(2786).

After modifying Foo to return JSX like this

function Foo({ obj: { key } }) {
  return <div>{key}</div>;
}

The function throws the error you wanted.

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

Comments

0

TypeScript should be generating an error when you try to do that. The type inferences are pretty good. Maybe you have a problem with your eslint config? If you run the TypeScript compiler (not just eslint) does it generate any errors?

Well either way, a better way to type your function/React component props is to be more explicit, like this:

function Foo({
  obj: { key },
}: {
  obj: {
    key: number;
  }
}) {
  // etc.
}

or, a bit easier to digest for some people's tastes:

type FooProps = {
  obj: {
    key: number;
  }
}

function Foo({obj: {key}}: FooProps) {
  // etc
}

The basic pattern is function MyComponent(props: MyPropsType) {}

Comments

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.