Search code examples
reactjstypescriptreact-props

Issues with props in a function component with TypeScript



Edit:

Now I get this error:

Property 'addColumns' does not exist on type 'PropsWithChildren<{ myProps: any; }>'.ts(2339)

With this code:

Const Djitsheet: React.FC<{ myProps }> = (props) => {  
 console.log('🥨🥨🥨🥨', props) 
  let dataToPass: Array<any> 
   let addColumnsToPass: boolean = props.addColumns  
 let addRowsToPass: boolean = props.addRows

Original:

I am attempting to convert a JSX React function component into a TSX one. This is for an internship, and it's my first attempt at such. I just need to get it started and then I will know where to go from there...

I am getting this error in VS Code with my TS React FC...

Type '{ (props: myProps): JSX.Element; defaultProps: Partial<{ props: myProps; }>; propTypes: React.WeakValidationMap<{ props: myProps; }>; }' is not assignable to type 'FC<{ props: myProps; }>'.
  Types of parameters 'props' and 'props' are incompatible.
    Type 'PropsWithChildren<{ props: myProps; }>' has no properties in common with type 'myProps'.ts(2322)

Here is my code.

interface myProps {
  id?: string
  size?: Array<number>
  data?: Array<any>
  headers?: Array<any>
  addColumns?: boolean
  addRows?: boolean
  readonly?: boolean
  snapToData?: boolean
}

const Djitsheet: React.FC<{ props: myProps }> = (props: myProps) => {

return <h1>Hello, from TSX</h1>
}

Djitsheet.defaultProps = {
  id: `my-sheet`,
  size: [4, 4],
  data: undefined,
  headers: [],
  addColumns: true,
  addRows: true,
  readonly: false,
  snapToData: false
}

Djitsheet.propTypes = {
  id: PropTypes.string,
  size: PropTypes.array,
  data: PropTypes.array,
  headers: PropTypes.array,
  addColumns: PropTypes.bool,
  addRows: PropTypes.bool,
  readonly: PropTypes.bool,
  snapToData: PropTypes.bool
}

I also get an error with the id prop in VS code that says:

Type '{ id: string; size: number[]; data: undefined; headers: undefined[]; addColumns: boolean; addRows: boolean; readonly: boolean; snapToData: boolean; }' is not assignable to type 'Partial<{ props: myProps; }>'.
  Object literal may only specify known properties, and 'id' does not exist in type 'Partial<{ props: myProps; }>'.ts(2322)

Solution

  • As you pass the interface to the declared Functional Component avoid passing it as a nested object.

    Let's look closely at your "edit" version:

    // Const Djitsheet: React.FC<{ myProps }> = (props) => {
    
    // pass "interface" the same way you pass "type"
    Const Djitsheet: React.FC<myProps> = (props) => {
      console.log('🥨🥨🥨🥨', props) 
      let dataToPass: Array<any>;
      let addColumnsToPass: boolean = props.addColumns;
      let addRowsToPass: boolean = props.addRows;
      // ...
    }