I want to declare a React.CssProperties prop to my component, but utilizing PropTypes. So far, I can make it works with PropTypes.object
. But then when I use the component, I cannot get css property type hint (ex. style like width, color, etc). Also, I have to manually cast it to React.CssProperties when assigning the prop to element.
Is there a way to declare a type like React.CssProperties with PropeTypes in Typescript?
import React from 'react';
import PropTypes, {InferProps} from "prop-types";
const propTypes = {
text: PropTypes.string,
style: PropTypes.object,
};
type Props = InferProps<typeof propTypes>;
const MyButton = ({text, style}: Props) => {
return (
<button style={style as React.CSSProperties} />
)
})
import React from 'react';
const App = () => {
return (
<MyButton style={{width: '100px'}}>{text}</button> // no type hint in IDE when typing width, color..etc
)
}
export App
2
Answers
Here is the optimize code:
Here is the result:
you not need to import propTypes from propTypes. simply use type
Hope this help you