我正在使用 Typescript 和 Material-UI 我想为这样的变量声明组件类型
import MoreVert from '@material-ui/icons/MoreVert'
import { SvgIconProps } from '@material-ui/core/SvgIcon';
let myIcon: SvgIconProps = <MoreVert />; // does not work
但我收到错误:
[ts]
Type 'Element' is not assignable to type 'SvgIconProps'.
Types of property 'type' are incompatible.
Type 'string | ComponentClass<any> | StatelessComponent<any>' is not assignable to type 'string'.
Type 'ComponentClass<any>' is not assignable to type 'string'.
这就是 SvgIcon.ts 的 样子。我究竟做错了什么?
import * as React from 'react';
import { StandardProps, PropTypes } from '..';
export interface SvgIconProps
extends StandardProps<React.SVGProps<SVGSVGElement>, SvgIconClassKey> {
color?: PropTypes.Color | 'action' | 'disabled' | 'error';
component?: React.ReactType<SvgIconProps>;
fontSize?: 'inherit' | 'default' | 'small' | 'large';
nativeColor?: string;
titleAccess?: string;
viewBox?: string;
}
export type SvgIconClassKey =
| 'root'
| 'colorSecondary'
| 'colorAction'
| 'colorDisabled'
| 'colorError'
| 'colorPrimary'
| 'fontSizeInherit'
| 'fontSizeSmall'
| 'fontSizeLarge';
declare const SvgIcon: React.ComponentType<SvgIconProps>;
export default SvgIcon;
原文由 Murat Karagöz 发布,翻译遵循 CC BY-SA 4.0 许可协议
参考: https ://www.typescriptlang.org/docs/handbook/jsx.html
我丢失所有类型信息的原因
JSX.Element
是因为它扩展了React.ReactElement<any>
类型为any
。为了解决这个问题,我像这样使用它现在我有了包含所有类型信息的元素。