简体   繁体   中英

Typescript: prevent extra keys for a React prop object?

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?

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

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) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM