Balázs Édes
Balázs Édes

Reputation: 13807

Typescript React component decorator

It might be a rookie mistake, but I'm trying to create a simple class decorator using typescript for a React component, like this:

import * as React from 'react'

interface Greeter {
  sayHello: boolean
}

const greet = (arg: Greeter) => (Comp: React.Component) => {
  // do some stuff
}

@greet({ sayHello: true })
class MyComp extends React.Component<any, any> {
  render() {
    return <div>Hi</div>
  }
}

But I'm getting a compile error saying

Argument of type 'typeof MyComp' is not assignable to parameter of type 'Component<{}, {}>'.

What exactly am I doing wrong here? Am I missing something with the decorator syntax?

Upvotes: 2

Views: 5515

Answers (2)

user2562438
user2562438

Reputation: 33

I'm not sure when this was added, but in newer versions of @types/react you can also do React.ComponentType e.g.

const greet = (arg: Greeter) => (Comp: React.ComponentType) => {
  // do some stuff
}

Upvotes: 1

Oblosys
Oblosys

Reputation: 15096

As you're passing the class to greet, rather than an object of that class, add a typeof:

const greet = (arg: Greeter) => (Comp: typeof React.Component) => {
  // do some stuff
}

Upvotes: 3

Related Questions