Search code examples
reactjstypescriptreact-nativereact-proptypes

Convert the PropTypes compatible to TypeScript


What I'm trying to do is to pass a props and be compatible with both PropTypes and TypeScript.

I have this Props inputGroupAddon:

      <TextField
        value={value}
        inputGroupAddon={{
          prepend: {
            icon: 'First',
            class: ''
          },
          append: {
            icon: 'Last',
            class: ''
          }
        }}
      />

Which should be compatible to propTypes:

TextField.propTypes = {
  inputGroupAddon: PropTypes.objectOf(
    PropTypes.shape({
      icon: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
      class: PropTypes.string
    })
  )
}

How can I make this compatible with TypeScript?

type inputGroup = {
  icon: Element | string
  class: string
}

export type TextFieldType = {
  value: string | any
  inputGroupAddon: inputGroup | null
}

Solution

  • Based on your props assignment it looks like this might work:

    type inputGroup = {
      icon: Element | string
      class: string
    }
    
    type InputGroupAddon = {
      prepend?: inputGroup
      append?: inputGroup
    }
    
    export type TextFieldType = {
      value: string | any
      inputGroupAddon: InputGroupAddon
    }