简体   繁体   English

使用 rest 语法解构道具时,Typescript 无法推断道具

[英]Typescript fails to infer props when destructuring props with rest syntax

I have a custom generic type that uses React's ComponentProps internally.我有一个自定义泛型类型,它在内部使用 React 的ComponentProps
When I create the type of a component's props using this custom type, TS behaves strangely.当我使用这种自定义类型创建组件道具的类型时,TS 的行为很奇怪。
Here is a simple example:这是一个简单的例子:
Codesandbox Link 代码沙盒链接

You can see in the link above that when I use PropsWithAs generic type, TS only understands that fallbackText is in the props if I access it directly.您可以在上面的链接中看到,当我使用PropsWithAs泛型类型时,TS 只有在我直接访问它时才知道fallbackText在 props 中。 But it fails to get the fact that fallbackText is in in the rest variable when I use rest syntax.但是当我使用 rest 语法时,它没有得到fallbackTextrest变量中的事实。

type Props<T extends ElementType = "div"> = PropsWithAs<
  T,
  {
    fallbackText: string;
    counter: number;
  }
>;

const Foo = <T extends ElementType>(props: Props<T>): JSX.Element => {
  // fallbackText is present and identified by TS here without any issue:
  const { fallbackText } = props;
  
  const { counter, ...rest } = props;

  // But TS doesn't see that `rest` also includes fallbackText here:
  return <Bar {...rest} />;
};

The problem seems to be the definition of PropsWithAs.问题似乎是 PropsWithAs 的定义。 I don't really understand why you are using & Omit<ComponentProps<T>, keyof U> , it seems to be the contrary of what you want.我真的不明白你为什么使用& Omit<ComponentProps<T>, keyof U> ,这似乎与你想要的相反。

Anyways, if you remove that piece of code everything should work just fine.无论如何,如果您删除那段代码,一切都应该可以正常工作。

I believe I found the problem我相信我找到了问题

Omit<ComponentProps<T>, keyof U>

this is because omit remove from the type the keys you want ts document about omit It means that you remove from the T the U keys it doesn't mean you gonna have those keys in the rest if they do not exist in the T这是因为 omit remove from the type the keys you want ts document about omit这意味着您从 T 中删除了 U 键这并不意味着您将在 rest 中拥有这些键,如果它们不存在于 T

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

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