Category Archives: TypeScript

React & Material UI “Invalid hook call. Hooks can only be called inside of the body of a function component”

When looking through some examples of writing Material UI code within React and using TypeScript (within a .tsx file to be precise) you might come across an error at runtime such as “Invalid hook call. Hooks can only be called inside of the body of a function component”.

Here’s an example of the code which causes this error

import React, { Component }  from "react";
import AddIcon from "@material-ui/icons/Add";
import { Fab } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles(theme => ({
   fab: {
      margin: theme.spacing(1),
   },
}));

const classes = useStyles();

export default class SampleComponent extends Component<{}, {}> {
   public render() {
      return (
         <div>
            <Fab color="primary" aria-label="Add" className={classes.fab}><AddIcon /></Fab>
         </div>
       );
   }
}

What we need to do is wrap the useStyles code in a function and replace the code which uses it, so for example

const SampleFab = () => {
   const classes = useStyles();
   return <Fab color="primary" aria-label="Add" className={classes.fab}><AddIcon /></Fab>;
}

export default class SampleComponent extends Component<{}, {}> {
   public render() {
      return (
         <div>
            <SampleFab />
         </div>
      );
   }
}

This also shows how we can create reusable components from just a simple function.

Method overloading in Typescript

Method overloading within TypeScript feels slightly strange, especially if you’re coming from a language such as C#.

In essence we declare the overloads but only have a single implementation which should handle the alternate arguments from the declared overloads by checking the types passed in. Don’t worry, we’ll look at an example which will make this clear.

The first thing to know about TypeScript overloads is if we declare overloads with the same number of arguments in the methods, these will be transpiled to JavaScript and the static types of the arguments is lost.

In other words, if you have

class Options {
   static if<T>(value: T, condition: boolean): void {
   }
   static if<T>(value: T, numberParameter: number): void {
   }
}

the type information would be lost when transpiled, effectively meaning both methods would look like this

static if(value, condition);

So how do we do method overloading in TypeScript?

We can create method overloads with different numbers of arguments within TypeScript, but we “declare” the method signatures without implementations, for example

class Options {
   static if<T>(value: T, condition: boolean): void;
   static if<T>(value: T, numberParameter: number, stringParameter: string): void;

   // implementation to follow
}

As can be seen we have two overloads of the if method taking two and three arguments respectively, but these methods have no implementation. Instead we need to create another overload which can take all the arguments.

In this case we have a method with two arguments and one with three, hence our implementation needs to take three arguments. We then need to either match the argument types (if all overloads take the same type for any argument) or handle different types via a union or an any type and then check the type passed into the method using typeof or instanceof.

So for example, here’s an implementation of a method which can handle the types passed to either of the “declared” overrides

static if<T>(value: T, stringOrNumberParameter: any, stringParameter?: string): void {
   if (stringOrNumberParameter && typeof stringOrNumberParameter == "number") {
      // handle the second argument as a number
   }
   else {
      // handle the second argument as a string
   }
}

Notice how the third argument needs to be optional or have a default so that we can still use the two argument overload.

Hence, we end up with the following

class Options {
   static if<T>(value: T, condition: boolean): void;
   static if<T>(value: T, numberParameter: number, stringParameter: string): void;
    
   static if<T>(value: T, stringOrNumberParameter: any, stringParameter?: string): void {
      if (stringOrNumberParameter && typeof stringOrNumberParameter == "number") {
         // handle the second argument as a number
      }
      else {
         // handle the second argument as a string
      }
   }
}

We can implement overloads with the same number of arguments, within TypeScript. Again the types are lost once transpiled, but let’s take this example

function run(option: null): null;
function run(option: number): number;
function run(option: string): string;
function run(option: any): any {
  if(typeof option == "string") {
    // string implementation
  }
}

which again gets transpiled without types to

function run(option) {
}

however during development the types are respected. In such scenarios one might also use unions, such as

function run(option: string | number | null) {
}

Zero to web with TypeScript, webpack and more

This post is a little long but the aim is to cover creating a simple TypeScript/HTML website without using any frameworks but using a whole bunch of standard tools.

The website will be pathetically unimpressive because I want to solely concentrate on just getting the various technologies working together.

We’ll be using Visual Code as the editor. We’ll be using TypeScript, ESLint and Jest (as per previous posts on this topics) and we’ll be using webpack to both create a distribution of our code and to host our code.

Creating the basics

  • Create the project’s folder, mine’s zerotoweb
  • Open Visual code against the new folder
  • Use the key combination (on mine it’s CTRL + ‘ on Windows) to open the terminal within Visual Code or if you prefer open a command prompt and navigate to the the folder you created
  • run yarn init –yes within the terminal. This will create the package.json file
  • run tsc –init within the terminal to create the tsconfig.json file
  • Change tsconfig.json to the following contents
    {
      "compilerOptions": {
        "target": "es6",
        "outDir": "./public",
        "rootDir": "./src",
        "allowJs": true,
        "skipLibCheck": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "noImplicitAny": false
      },
      "include": [
        "src"
      ],
      "exclude": [
        "node_modules"
      ]
    }
    
  • Next create the src folder off of the root
  • Add a file named index.ts to src folder and add the following code
    class App {
        getSalutation() {
            return "Hello World"
        } 
    }
    
    let app = new App();
    console.log(app.getSalutation());
    
  • We’ll want to run from node, which currently doesn’t support es6 so we’ll need to add babel, so run
    • yarn add babel-cli -D
    • yarn add babel-preset-es2015 -D
    • yarn add babel-preset-env -D
  • Let’s now add a couple of scripts to package.json
    "scripts": 
    {
       "build": "tsc --watch", 
       "start": "babel-node --presets es2015 ./public/index.js"
    }
    
  • Now we need to add a configuration file for babel, so add a .babelrc file to the root folder and put the following within it
    {
       "presets": ["env"]
    }
    
  • Next we want to add ESLint (this section is a duplication of the previous post but is here for completeness), so run the following
    • yarn add eslint -D
    • yarn add @typescript-eslint/parser -D
    • yarn add @typescript-eslint/eslint-plugin -D
    • Add a .eslintrc.js file to the root folder, place the following into the file
      module.exports = {
          "parser": '@typescript-eslint/parser',
          "plugins": ['@typescript-eslint'],
          "extends": ['plugin:@typescript-eslint/recommended'],
          "rules": {
              "@typescript-eslint/no-parameter-properties": "off",
              "@typescript-eslint/no-explicit-any": "off"
          }
      };
      
    • Now add the following “lint”: “eslint ./src/*.ts” to the scripts section of the package.json
  • Now run yarn build
  • Lets see some output, so run yarn start. If all went well you should see Hello World output.

Adding tests

I’ve covered installing Jest for testing React applications previously but let’s see the steps to take to get everything installed for our non-React world

  • yarn add jest -D
  • yarn add @types/jest -D
  • yarn add ts-jest -D
  • yarn add @types/node -D (not sure about this one)
  • Add __tests__ under the src folder
  • Add TypeScript tests to the __tests__ folder, convention suggests {name}.test.ts for the filenames
  • Add “test”: “jest” to the scripts section of packages.json if you want to run the tests yourself (i.e. no plugin or watch)
  • Finally in the root folder add the file jest.config.js with the following code
    module.exports = {
        roots: ['./src'],
        transform: {
          '^.+\\.tsx?$': 'ts-jest',
        },
        testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
        moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
      }
    

In Visual Code the plugin for Jest (Use Facebok’s Jest With Pleasure) from Orta is very useful to have.

Test coverage

Jest includes an option for running code coverage, simply change your packages.json script to

  • “test”: “jest –coverage”

Adding webpack

Next up we’re going to create our basic web site, extending on what we’ve already covered.

  • Create folder name public off of the root folder
  • Add a file named index.html to public folder, here’s the HTML
    <html>    
        <body>
            <script src="./index.js"></script>
        </body>
    </html>
    
  • Run the following commands
    • yarn add webpack -D
    • yarn add webpack-cli -D
    • yarn add webpack-dev-server -D
    • yarn add babel-loader@7 -D (@7 was required for bable-core)
    • yarn add babel-core -D
  • Create a webpack.config.js in the root folder here’s mine
    var path = require("path");
    module.exports = {
       entry: {
         app: ["./public/index.js"]
       },
      output: {
        path: path.resolve(__dirname, "build"),
        filename: "bundle.js"
      },
      devServer: {
        port: 9000,
        contentBase: "./public"
      },
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /(node_modules)/,
            use: {
              loader: "babel-loader",
              options: {
                presets: ["babel-preset-env"]
              }
            }
          }
        ]
      }
    };
    
  • Now replace the console.log line within the index.ts file with the following
    document.body.innerHTML = app.getSalutation();
    
  • Replace the previously created “start” script with “start”: “webpack-dev-server –open” in packages.json “scripts” section
  • Let’s run yarn start and if all went well you should see a browser window open and display our HTML page with the JavaScript created from our TypeScript file displayed

Time to create bundles

We’re going to use webpack to create some distribution bundles

  • Run the following commands
    • yarn add express -D
    • yarn add webpack-dev-middleware -D
    • yarn add html-webpack-plugin -D
    • yarn add clean-webpack-plugin -D
  • Change the webpack.config.json to
    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const CleanWebpackPlugin = require('clean-webpack-plugin');
    
    module.exports = {
      mode: 'development',
      entry: {
        app: './public/index.js'
      },
      devtool: 'inline-source-map',
      devServer: {
        port: 9000,
        contentBase: './dist'
      },
      plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
          title: 'Demo'
        })
      ],
      output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/'
      }
    };
    
  • Add “bundle”: “webpack” to the scripts section of the packages.json file. This will create a dist folder with, both the HTML file and the JS files we’ve created and generated

Minifying

You’ll notice that the JavaScript file generated in the previous steps is not exactly small, containing comments, whitespace etc. So we’re going to minify it for distribution.

  • Run yarn add babel-minify-webpack-plugin -D
  • Within the webpack.config.js file, comment out devtool: ‘inline-source-map’,
  • Add this line to the top of the file
    const MinifyPlugin = require("babel-minify-webpack-plugin");
    
  • Add new MinifyPlugin to the file, so it looks like this
    plugins: [
       new CleanWebpackPlugin(),
       new HtmlWebpackPlugin({
          title: 'Demo'
       }),
       new MinifyPlugin()
    ],
    
  • Finally, run our script yarn bundle

Trying an alternate minify

Let’s try terser

  • Run yarn add terser-webpack-plugin -D
  • Add this line to the top of webpack.config.js
    const TerserPlugin = require('terser-webpack-plugin');
    
  • Add the following to webpack.config.js
    optimization: {
        minimizer: [new TerserPlugin({
          extractComments: true,
          test: /\.js(\?.*)?$/i,
        })],
      },
    

The optimization will need to be run webpack in production mode, i.e. webpack –mode=production or webpack-dev-server –open –mode=production or in webpack.config.js set mode: ‘production’.

Hence using yarn we can run yarn bundle –mode=production to see the bundle.js has been minified using terse. Obviously you can remove the new MinifyPlugin() also at this point if using TerserPlugin.

Using ESLint on TypeScript files

Assuming you already have a project set-up. If you don’t have typescript within your node modules, add it using

  • yarn add typescript

Next up we’ll add eslint and it’s typescript plugins (to the dev dependencies)

  • yarn add –dev eslint
  • yarn add –dev @typescript-eslint/parser
  • yarn add –dev @typescript-eslint/eslint-plugin

ESList uses a configuration file in the shape of a .eslintrc.js file which should be placed in root folder of your project. Below is a sample

module.exports = {
    "parser": '@typescript-eslint/parser',
    "plugins": ['@typescript-eslint'],
    "extends": ['plugin:@typescript-eslint/recommended'],
    "rules": {
        "@typescript-eslint/no-parameter-properties": "off",
        "@typescript-eslint/no-explicit-any": "off"
    },
};

In the above we’ve turned off a couple of rules (the rule name will be listed alongside output from eslint when it’s run).

Now, to run eslint we use the following command

.\node_modules\.bin\eslint ./src/*.ts

References

ESLint Rules
ESLint Plugin

Generators in JavaScript and TypeScript

Generators within JavaScript (and TypeScript) are similar to C# IEnumerable’s such that you can yield a value multiple times from a generator function (in either JavaScript or TypeScript), i.e.

function* someValues() {
    yield 1;
    yield 2;
    yield 3;
}

or within a TypeScript class we can write

export default class MyClass {
    *someValues() {
       yield 1;
       yield 2;
       yield 3;
    }
}

To use the someValues function we can loop using

for(let i of someValues()) {
    console.log(i);
}

Each item returned is a type of { value, done }, so for example

var values = someValues();

console.log(values.next());
console.log(values.next());
console.log(values.next());
console.log(values.next());

which would output

{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
{ value: undefined, done: true }

Using lodash in TypeScript

Was trying to use lodash and couldn’t seem to get Visual Code to build my TypeScript files correctly, so here’s how to get it working…

Add the following esModuleInterop to your tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "esModuleInterop": true,
        "sourceMap": true
    }
}

and then you can use

import _ from "lodash";

Otherwise you can use the following if esModuleInterop doesn’t exist or is set to false

import * as _ from "lodash";

Promises in JavaScript/TypeScript

Promises, are analogous to futures or tasks (if you background is C#) and are used for asynchronous code.

I’m using TypeScript at the moment (as part of learning Angular 2) but I’ll try to list code etc. in both JavaScript and TypeScript, solely to demonstrate the syntax. The underlying functionality will be exactly the same as (of course) TypeScript transpiles to JavaScript anyway.

The syntax for a promise in JavaScript looks like this

let promise = new Promise((resolve, reject) {
   // carry out some async task
   // then resolve or reject
   // i.e. resolve(result);
   // and/or reject("Failed");
});

As you can see in the above code, we can (in essence) return a success, with resolve or a failure, with reject.

In some situations we might simply wish to immediately resolve or reject without actually executing any asynchronous code.

In such situations we can use the methods Promises.resolve and/or Promise.reject method calls, i.e.

// in JavaScript
function getData() {
   return Promise.resolve(data);
   // or 
   return Promise.reject("Cannot connect");
}

// in TypeScript
getData(): Promise<MyDataType> {
   return Promise.resolve(data);
   // or
   return Promise.reject("Connot connect);
}

As you can see the difference between TypeScript and JavaScript (as one might expect) is the strong type checking/expectations.

Using the results from a Promise

As a promise is potentially going to be taking some time to complete we need a way to handle continuations, i.e. what happens when it completes.

In C# with have ContinueWith, in JavaScript we have then, hence our code having received a Promise might look like this

let promise = getData();

promise.then(result => {
   // do something with the result
}).catch(reason => {
   // failure, so something with failure
});

There are other Promise methods, see promise in JavaScript but this should get us up and running with the basics.

Using jQuery in TypeScript

As somebody who mainly develops in C# I do miss strong typing when using JavaScript. So I’ve started to use TypeScript which solves this. But let’s face it, this would be of little use without jQuery (and other frameworks). So here’s the steps to get jQuery running with TypeScript.

  1. If you have already installed TypeScript, grab the latest VS2012 integration from http://www.typescriptlang.org/
  2. Next up, create a new project, navigate to Other Languages | TypeScript and create a new TypeScript project
  3. From the References section in the solution explorer, right mouse click and select Manage NuGet Packages and search for jquery.TypeScript.DefinitelyType and install – this will install a .ts file which includes the jQuery TypeScript definition to allows us to work with code completion
  4. Now either from NuGet, install jQuery or download from http://jquery.com/
  5. To reference the jQuery TypeScript file put /// at the top of the app.ts file, this will allow VS2012 to reference the types in the .ts file
  6. You’ll need to add a script to the default.htm file

Now we’ve got jQuery up and running in TypeScript.

Note: One problem I found on one of my machines was the code complete didn’t work for TypeScript, reading up on this on it appeared (as suggested in one of the posts) that MySQL Connector Net 6.6.5 was causing the problem. Open Control Panel | Programs | Programs and Features, location My SQL Connector 6.6.5 if its installed. Right mouse click on it and select Change and remove the Visual Studio Integration.