How declare a type with PropType?

273 Views Asked by At

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

There are 2 best solutions below

4
ankushlokhande On

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

3
Sahib Khan On

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