reactjstypescriptobject-destructuring

Enforcing TSX prop type inline for function declaration which declares props using object destructuring


I have a custom Type

export class MyClass {
  name: string;
  img: string;

  constructor(name: string) {
    this.name = name;
    this.img = `/images/${name}.jpg`;
  }
}

I have a stateless functional component which takes that type as a parameter

export default (issue: Issue) => {
...
}

And when I try to create that stateless functional component

<MagazineCard issue={issues[0] as Issue} />

I get the error

Type '{ issue: any; }' is not assignable to type 'IntrinsicAttributes & Issue'.

There is a solution below, but I felt I should leave this material up for other's who might see this question for alternative solutions and deeper understanding

Object destructuring when initializing the JSX, ex:

<MagazineCard {...issues[0]} />

Create an interface for the arguments of my stateless functional component.

Note: types don't need to be specified

Proptypes

MagazineCard.propTypes = {
  issue: Issue
}

Solution

  • This is how it's done

    export default ({issue} : {issue : Issue}) => (
        //...Your JSX component
    )
    

    I was confused because it seemed over complicated to me, so I made a post on reddit asking why this is the syntax for doing it