This is part of this series of blog posts introducing TypeScript and React. Here’s Part 1.
TypeScript’s inferred typing gives you some flexibility on how you declare “Stateless Function Components”. Here are some examples.
Simple:
If you are wondering what the extra curly braces are for in the parameters of the three examples,
myvar
and onClick
are extracted from props via
destructuring assignment. This
next one is a little strange, because the types are declared inline.
With inline declaration of props:
The thing that may be unclear about that syntax is that this types the props
object, and therefore
only types the myVar
and onClick
variables indirectly. Here’s a
fuller explanation. I think it’s
clearer to use an interface instead:
With an interface for props:
Verbose:
It’s good to know what kind of types are being created, especially when combining these with higher-order functions. This is more explicit:
Very Verbose
This is a little unwieldy. Probably I wouldn’t ever explicitly declare that you can click on either an HTMLElement or a JSX.Element, or that I’m wrapping a div type:
Tests
For completeness, here are the tests:
More Reading
- Part 1: Getting Started with TypeScript and React
- Part 2: Simple React Components in TypeScript
- Part 3: Stateless React Components in TypeScript
- Part 4: React’s Higher Order Controls in TypeScript
- Coming soon: TypeScript with Redux; Testing & Continuous Deployment