gpt4 book ai didi

javascript - Material-UI:如何使用 typescript 为 React.ComponentType

声明类型

转载 作者:行者123 更新时间:2023-11-30 14:22:22 24 4
gpt4 key购买 nike

我正在使用 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'.

This is how the 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;

最佳答案

引用:https://www.typescriptlang.org/docs/handbook/jsx.html

By default the result of a JSX expression is typed as any. You can customize the type by specifying the JSX.Element interface. However, it is not possible to retrieve type information about the element, attributes or children of the JSX from this interface. It is a black box.

我使用 JSX.Element 丢失所有类型信息的原因是因为它扩展了 React.ReactElement<any>其类型为 any .为了解决这个问题,我像这样使用它

 let myIcon: React.ReactElement<SvgIconProps> = <MoreVert />; 

现在我有了包含所有类型信息的元素。

关于javascript - Material-UI:如何使用 typescript 为 React.ComponentType<P> 声明类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52537285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com