Master React with Typescript and Unit Tests

Photo by freddie marriage on Unsplash

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.

Advantages

TypeScript can check plan Javascript and JSDoc annotations

Disadvantages

  • not a full-featured language
  • typing function arguments and return types not guaranteed
JSDoc is useful for comment styling and tags like @deprecated that marks a method as deprecated in the project.

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.

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.

Javascript course — Language basics, variables, data types

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.

functions with an object argument

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.

Javascript course — Javascript the good parts frequently used in React

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

Best practices for Javascript projects

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.

Codesandbox

Tasks

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

Result

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

Please provide feedback here link.


Master React with Typescript and Unit Tests was originally published in ableneo Technology on Medium, where people are continuing the conversation by highlighting and responding to this story.