Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
15
rated 0 times [  18] [ 3]  / answers: 1 / hits: 19071  / 6 Years ago, thu, september 27, 2018, 12:00:00

I am using Typescript and Material-UI I want to declare the component type for a variable like this



import MoreVert from '@material-ui/icons/MoreVert'
import { SvgIconProps } from '@material-ui/core/SvgIcon';

let myIcon: SvgIconProps = <MoreVert />; // does not work


But I am getting the error:



[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 looks like. What am I doing wrong?



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;

More From » typescript

 Answers
4

Reference: 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.




The reason why I lose all type information with JSX.Element is because it extends React.ReactElement<any> which has the type of any. To fix this I used it like this



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


Now I have the element with all the type information.


[#53421] Friday, September 21, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
faithemilys

Total Points: 418
Total Questions: 100
Total Answers: 114

Location: North Korea
Member since Fri, Nov 4, 2022
2 Years ago
;