diff --git a/docs/src/pages/guides/typescript.md b/docs/src/pages/guides/typescript.md index 204f29085ab0d0..18bd2206927333 100644 --- a/docs/src/pages/guides/typescript.md +++ b/docs/src/pages/guides/typescript.md @@ -36,10 +36,10 @@ const DecoratedSFC = decorate(({ text, type, color, classes }) => ( )); ``` -Class components are a little more cumbersome. They require more type annotations, and due to a [current limitation in TypeScript's decorator support](https://github.com/Microsoft/TypeScript/issues/4881), `withStyles` can't be used as a class decorator. Instead we decorate a class component like so: +Class components are a little more cumbersome. Due to a [current limitation in TypeScript's decorator support](https://github.com/Microsoft/TypeScript/issues/4881), `withStyles` can't be used as a class decorator. Instead we decorate a class component like so: ```ts -const DecoratedClass = decorate( +const DecoratedClass = decorate( class extends React.Component> { render() { const { text, type, color, classes } = this.props @@ -52,3 +52,37 @@ const DecoratedClass = decorate( } ); ``` + +Note that in the class example you didn't need to annotate `` in the call to `decorate`; type inference took care of everything. One caveat is that if your styled component takes _no_ additional props in addition to `classes`. The natural thing would be to write + +```ts +const DecoratedNoProps = decorate( + class extends React.Component> { + render() { + return ( + + Hello, World! + + ) + } + } +); +``` + +Unfortunately TypeScript infers the wrong type in this case and you'll have trouble when you go to make an element of this component. In this case you'll need to provide an explicit `{}` type argument, like so: + +```ts +const DecoratedNoProps = decorate<{}>( // <-- note the type argument! + class extends React.Component> { + render() { + return ( + + Hello, World! + + ) + } + } +); +``` + +To avoid worrying about this edge case it may be a good habit to always provide an explicit type argument to `decorate`. diff --git a/test/typescript/styling-comparison.spec.tsx b/test/typescript/styling-comparison.spec.tsx index d6f881a3443195..2a447f49383004 100644 --- a/test/typescript/styling-comparison.spec.tsx +++ b/test/typescript/styling-comparison.spec.tsx @@ -36,5 +36,18 @@ const DecoratedClass = decorate( } ); +const DecoratedNoProps = decorate<{}>( + class extends React.Component> { + render() { + return ( + + Hello, World! + + ) + } + } +); + const sfcElem = ; const classElem = ; +const noPropsElem = ;