我有一个使用as
道具的组件,应该从中推断出其余的道具类型:
import React from 'react';
import s from './index.module.scss';
export type LayoutProps<As extends React.ComponentType<any> | keyof JSX.IntrinsicElements> = {
as: As;
} & React.ComponentProps<As>;
export function Layout<As extends React.ComponentType<any> | keyof JSX.IntrinsicElements>({
as: Component = 'div',
children,
className = '',
...props
}: LayoutProps<As>) {
return (
<Component className={`${s.layout} ${className}`} {...props}>
{children}
</Component>
);
}
这对于标准的React组件很好用,例如以下内容将引发错误Type 'number' is not assignable to type 'string | undefined'
:
import React from 'react';
import { Link } from 'react-router-dom';
const Example = () => <Layout as={Link} title={5}>Hello</Layout>;
这在实际上应该抛出相同错误时起作用:
import React from 'react';
const Example = () => <Layout as="a" title={5}>Hello</Layout>;
我在做什么错了?
谢谢!