0

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
Ken White
  • 123,280
  • 14
  • 225
  • 444
Arst
  • 3,098
  • 1
  • 35
  • 42
  • I just wondering. Why would you need prop types when you already have TypeScript? – Joshua Feb 22 '23 at 01:59
  • 1
    Some said they are different.. https://stackoverflow.com/questions/41746028/proptypes-in-a-typescript-react-application. Typescript validates types at compile time, whereas PropTypes are checked at runtime. – Arst Feb 22 '23 at 02:00

2 Answers2

0

Here is the optimize code:

import { CSSProperties, FC } from 'react';

interface MyButtonProps {
  text: string;
  style?: CSSProperties;
}

const MyButton: FC<MyButtonProps> = ({ text, style }) => {
  return (
    <button style={style}>{text}</button>
  );
};

export default MyButton;

Here is the result: Expected Result

ankushlokhande
  • 870
  • 5
  • 20
  • @Arst Let me know if still face any issue or doubts? – ankushlokhande Feb 22 '23 at 02:41
  • My questions is about using PropTypes from 'prop-types' as the props definition... – Arst Feb 22 '23 at 03:35
  • Hi, You can achieve this without PropTypes from `prop-types`. Let me know if you want to achieve with `prop-types`, I'll share with this also. – ankushlokhande Feb 22 '23 at 14:50
  • 1
    If you have doubts related to which DataType is suitable in your case, checkout this blog: [proptypes vs types](https://medium.com/smallcase-engineering/proptypes-vs-types-in-typescript-45433990a8f9) – ankushlokhande Feb 22 '23 at 14:59
0

you not need to import propTypes from propTypes. simply use type

import React from 'react';


type PropTypes = {
  text: string,  
  style: any,
};

const MyButton = ({text, style}:  Props) => {
  return (
    <button style={style as React.CSSProperties} />
  )
})

Hope this help you