I have a custom generic type that uses React's ComponentProps
internally.
When I create the type of a component's props using this custom type, TS behaves strangely.
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. But it fails to get the fact that fallbackText
is in in the rest
variable when I use rest syntax.
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} />;
};
CodePudding user response:
The problem seems to be the definition of 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.
Anyways, if you remove that piece of code everything should work just fine.
CodePudding user response:
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