简体   繁体   English

Typescript:防止 React 道具 object 的额外键?

[英]Typescript: prevent extra keys for a React prop object?

When calling functions with object arguments, extra keys are forbidden:使用 object arguments 调用函数时,禁止使用额外的键:

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:但是,对于 React 功能组件,此错误不会触发:

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 用作示例中的组件时,出现错误'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) . '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像这样修改 Foo 以返回 JSX

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

The function throws the error you wanted. function 会抛出您想要的错误。

TypeScript should be generating an error when you try to do that.当您尝试这样做时,TypeScript应该会产生错误。 The type inferences are pretty good.类型推断非常好。 Maybe you have a problem with your eslint config?也许你的 eslint 配置有问题? If you run the TypeScript compiler (not just eslint) does it generate any errors?如果您运行 TypeScript 编译器(不仅仅是 eslint),它会产生任何错误吗?

Well either way, a better way to type your function/React component props is to be more explicit, like this:无论哪种方式,键入函数/React 组件道具的更好方法是更明确,如下所示:

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) {}基本模式是function MyComponent(props: MyPropsType) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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