Using TypeScript for ReactJS development is something I started a couple months ago and it’s a definite improvement on the speed of development and refactoring. In this blog post I want to write about why you should consider writing your React apps with TypeScript, how to get started and where to go to learn more.
The easies way to get set up is with
create-react-app. Specifically you will use it with the flag
--scripts-version=react-scripts-ts. What you will get will look like this:
.tsx extension instead of
Don’t forget to install the types of every library you add. For example when you
yarn add react-router-dom also do a
yarn add @types/react-router-dom.
As a bonus you get a full tslint setup for free. A linter is like somebody looking over your shoulder and telling you when you do things suboptimally. Examples are missing semicolons (debatable), mis-aligned code blocks or using single quotes instead of double quotes or vice versa (still a mystery to me). Be aware that by default this config is very strict. Got an unused import? Won’t let you compile. Two newlines in a row? Won’t let you compile. Used the unholy
console.log? Won’t let you… Nah, I’ll just nag you about it every time in the console myself.
TypeScript works best when it can infer of gets told about all types available. If that’s not the case it will implicitly assign the
any type to the variable in question. Implicit anys is something else our tslint (understandably) doesn’t like. If you just want to get the code compiled you can tell it the correct type or sloppily annotate it with
any (purists, don’t kill me please).
Let’s have a look at two React components, Parent and Child, to see some of the errors TypeScript can help with. As seen in the picture when you create a component you give it two templates (in square brackets). The first for your props, the second for your state.
First the Child component:
Here we see two errors: On Line 19 we try to extract the variables name and age from props but only name exists on props.
age would have the value
The other error is with state: State should hold two variables, text and count but on line 15 we initialize state only with one variable.
Now to the Parent component:
Just two simple errors we catch instantly now.
What about propTypes?
In my view prop types are superseded in TypeScript with the props template. With this you are very flexible in defining necessary, optional and default properties. You are able to define a property having one or more types, or even exact values (like
"green"|"blue" only accepting exactly those two strings).
Where to go from here
I’m going to write a post about TypeScript and Redux because resources on this are definitely lacking online right now. TypeScript has a lot more to offer, so I suggest to dig deeper. Try the TypeScript Homepage and the excellent open-source book TypeScript Deep Dive.