打字稿推断道具不适用于本征元素

时间:2020-05-04 02:54:46

标签: reactjs typescript

我有一个使用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>;

我在做什么错了?

谢谢!

0 个答案:

没有答案