Mur*_*göz 8 javascript typescript material-ui
我正在使用 Typescript 和Material-UI我想为这样的变量声明组件类型
import MoreVert from '@material-ui/icons/MoreVert'
import { SvgIconProps } from '@material-ui/core/SvgIcon';
let myIcon: SvgIconProps = <MoreVert />; // does not work
Run Code Online (Sandbox Code Playgroud)
但我收到错误:
[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'.
Run Code Online (Sandbox Code Playgroud)
这就是 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;
Run Code Online (Sandbox Code Playgroud)
Mur*_*göz 11
参考:https : //www.typescriptlang.org/docs/handbook/jsx.html
默认情况下,JSX 表达式的结果类型为 any。您可以通过指定 JSX.Element 接口来自定义类型。但是,无法从此接口检索有关 JSX 的元素、属性或子项的类型信息。它是一个黑匣子。
我丢失所有类型信息的原因JSX.Element是因为它扩展React.ReactElement<any>了类型为any. 为了解决这个问题,我像这样使用它
let myIcon: React.ReactElement<SvgIconProps> = <MoreVert />;
Run Code Online (Sandbox Code Playgroud)
现在我有了包含所有类型信息的元素。