Skip to content

Instantly share code, notes, and snippets.

@wiredprairie
Created April 21, 2018 02:25
Show Gist options
  • Save wiredprairie/a405d3eda19b8ceccb26f67ffe84b3fe to your computer and use it in GitHub Desktop.
Save wiredprairie/a405d3eda19b8ceccb26f67ffe84b3fe to your computer and use it in GitHub Desktop.
React and TypeScript decorator
import * as React from "react";
export function attachModel<T>(Model: { new (): T }) {
return function<Props, State>(Comp: React.ComponentClass<Props>) {
const ComponentModel = (Comp as any) as React.ComponentClass;
return class extends React.Component<Props, State> {
static displayName = `AttachedModel${ComponentModel.displayName ||
ComponentModel.name}`;
render() {
return <ComponentModel {...this.props} />;
}
};
};
}
interface Props {
demo: string;
}
@attachModel(ValidatedDataModel)
export class DemoComponent extends React.Component<Props> {
render() {
return <div>{this.props.demo}</div>;
}
}
/*
<DemoComponent demo="hello" />
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment