Jan Strnádek
Jan Strnádek

Reputation: 808

Write HOC as Decorator in TypeScript?

I am trying to create a decorator which takes an argument from React. Context provider, If I want to create HOC it is easy:

interface DashboardProps {
   user: User;
}

class Dashboard extends React.Component<DashboardProps> {
  render() {
     return (<span>{this.props.user.name}</span>);
  }
}

function withUser(WrappedComponent) {
  return class extends React.Component {
    render() {
      return (
        <UserContext.Consumer>
         {user => <WrappedComponent user={user} {...this.props}>}
        </UserContext.Consumer>
      );
    }
  }
}

export default withUser(Dashboard);

But I am not sure how to write it like a decorator:

@withUser
class Dashboard ...

Upvotes: 1

Views: 1398

Answers (1)

Ouyang Chao
Ouyang Chao

Reputation: 357

The type of class decorator in typescript looks like this:

declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;

Which means a class decorator function must return a same typed component, or nothing.

function withUser(WrappedComponent): void {
  return class extends React.Component {
    render() {
      return (
        <UserContext.Consumer>
         {user => <WrappedComponent user={user} {...this.props}>}
        </UserContext.Consumer>
      );
    }
  } as unknown as void;
}

Upvotes: 1

Related Questions