Master React with Typescript and Unit Tests

Marcel Mokos
Oct 17 · 5 min read

Most of the React components in our projects should be simple, reusable, testable and well-typed. Design components with well-defined properties that are easy to read and understand.

Enhance your developer productivity and experience. Use and promote relevant React abstractions and patterns formulated with the type-safety of Typescript. Types will help us avoid obvious problems in code. Tests for logic in the code are better than repetitive visual debugging.

Reason for type checking

The purpose of programming is to find a sequence of instructions that will automate the performance of a task for solving a given problem. Tasks are often created in distributed teams that need to communicate. Task inputs and outputs need to be well-documented contracts.

The ultimate goal is to make code easy to read, understand and validate. Distributed teams need strict static verification of the code. Types let you define interfaces between software components and gain insights into the behavior of existing JavaScript libraries.

Why Use types. (image source: link)

Advantages of types

  • improves code readability
  • provide valuable information about the code
  • better code analysis
  • static verification
  • early detection of errors
  • code autocomplete
  • robust dependable refactoring

JSDoc

JSDoc is a markup language used to annotate JavaScript source code files. Docs and cheatsheet.

Documenting types in Javascript using JSDoc comments is still valuable option. Editors, compilers and type checkers can read this information and provide you with error message hints.

JSDoc example

Advantages

TypeScript can check plan Javascript and JSDoc annotations

Disadvantages

  • not a full-featured language
  • typing function arguments and return types not guaranteed

Type checking With React PropTypes

read docs now in separate package prop-types. When an invalid value is provided for a prop, a warning will be shown during the run time in the JavaScript console.

Optional props

You can declare that a prop is a specific Javascript primitive.
By default, these are all optional.

Example with defaultProps and optional name of type string. Use optional properties only if the property has value in default props.

Example of use of prop-types.

Required props

The warning is shown if the prop isn’t provided.

Advantages

  • small standalone library focused on React components
  • can be removed in the production build

Disadvantages

  • missing typing for function arguments and return types
  • not practical outside React
  • you have to run the code to see the errors*
  • some editors will show errors/hints during development.
Why would you NOT use TypeScript?

Typescript

The same syntax as JavaScript with the benefit of optional types. Able to fully type functional arguments and return types.

Mr. Typed Data

basic types

TypeScript supports much the same types as you would expect in JavaScript.

If you want to refresh what you know about Javascript data types, please read the following article from my Javascript course.

Read full documentation on the https://www.typescriptlang.org/docs/handbook/basic-types.html

utility types

TypeScript provides several utility types to facilitate common type transformations. These utilities are available globally.

functions

Functions are the fundamental building block of any application in JavaScript.

Finally, fully typed function arguments and return types

functions with an object argument

Typed object argument function

The problem when the function takes more parameters

The function should have a maximum of one required and one optional parameter. Most of the time use object as a parameter/argument.

interface

The interface is a promise or a contract to implement a data shape. An interface can be extended. Interfaces with the same name are merged.

interface Point2D {
x: number;
y: number
}
interface Point3D extends Point2D {
z: number;
}

type

The type is a definition of a type of data that can be declared and assigned. It allows the creating of a new name for a primitive type.

type Coordinate = number;type Point2D = {
x: Coordinate;
y: Coordinate;
};
type Point3D = Point2D & {z: Coordinate};

typeof

In some cases is useful to just create type based on an existing object.

const defaultProps = {greeting: "Hello"};type Props = Readonly<typeof defaultProps & {name: string}>;// type Props = {readonly name: string; readonly greeting: string}

Advantages

  • language as a superset of Javascript
  • all the advantages of strong typing
  • can inference types
  • can read Javascript files, JSDoc comments
  • advanced types, generics, utility types
  • have strong community and large library of types for third party libraries

Disadvantages

  • can get complicated to type functions with generic types or components as arguments
No runtime checks

Before start using types some best practices

Assignment

Create a box similar to the one that Facebook uses for sharing.

FB share box

There is a codesandbox ready for you where you have fake data and examples of components.

Fake article data

Codesandbox

Start of the Assignment

Tasks

  • change the component to look like Facebook post
  • convert getBlog into separate hook useGetBlog

Result

Result of the Assignment

👏Clap, 👂follow for more awesome 💟#Javascript and ⚛️#automatization content.

Please provide feedback here link.

ableneo Technology

Application Development, Data Science, Experience Platforms

Marcel Mokos

Written by

I'm fanatic to next generation Javascript lambda, yield, async/await everything. I admire typescript and flow types. Javascript will ultimately rule the world.

ableneo Technology

Application Development, Data Science, Experience Platforms

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade