Monthly Archives: June 2019

Creating React components in TypeScript

By default we’ll usually create a React component (in a .tsx file) using a React.Component base class, for example

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

But as per my post here we can also create components through functions, which ofcourse makes sense when you see a .jsx file which tend to default to using functions.

Hence we can create the following

const MyButton = (props: any) => {
   return 
      <Button variant="contained" 
         color="secondary">{props.children}</Button>;
};

In the code above we’ve basically created a new component from the function which takes properties which are implicitly passed to the function via React, i.e. the code for using the above might look like this

<MyButton>Hello</MyButton>

The child elements are passed through to our function. In this case it’s just the string “Hello”.

Yarn and what not to commit to your source repos

When working with yarn you’ll find your source code folder includes the following files and folder (amongst others)

  • packages.json
  • yarn.lock
  • node_modules

If using TypeScript you may also have tsconfig.json.

The node_modules folder is basically everything downloaded via yarn that are either included within the packages.json or dependencies of those packages. So unless you’re fearful of versions of mdoules/dependencies becoming unavailable, this folder can be left out of source control, plus it can get big quickly.

The packages.json file should be committed as it obviously includes all the information regarding the packages used and their versions, but is also used for scripts etc.

Interestingly, I thought that yarn.lock should also be excluded as it’s generated by yarn, but according to Lockfiles should be committed on all projects.

If you have tsconfig.json, this file is a TypeScript configuration file. Hence this should be committed to ensure other team members are using the same configuration.

What about .vscode

If you’re using VSCode as your editor/development tool then you’ll notice that a .vscode folder is created in some cases with settings.json etc. within it.

Obviously whether you commit .vscode (or individual files within it) depends on whether you’re also aiming to commit shared settings etc. To my mind this would be a good thing as I use multiple machines for development and it’s an easy way for me to share settings between machines. This said if you’re a larger team it also might be useful to ensure everyone uses the same settings.

Using the Windows Subsystem for Linux

Whilst I have Linux machines available to me, they’re not always powered up or the remoting

See Windows Subsystem for Linux Installation Guide for Windows 10 for details on installing the WSL.

For completeness here’s the steps I took.

  • Run PowerShell as Admin and then execute the following

    Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
    
  • Go to the Microsoft Store and type Run Linux on Windows into the search text box. In the store currently, there’s the options of Ubuntu, openSUSE Leap 42, SUSE Linux Enterprise Server 12, Debian and Kali Linux.

    Install your preferred distro – I went for Ubuntu simply because that’s what I have on most of my Linux boxes.

  • Once installed you’ll need to go to the command prompt | Properties and select the Options tab. From here ensure that Use legacy console (requires relaunch) is unchecked.

Once everything is initialized you’ll be in the user’s (whatever user name you created) home folder – on Windows this folder is stored in C:\Users\{username}\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs\home

We can access the C drive using

cd /mnt/c

Running the Linux from Windows

When you want to run the Windows Subsystem for Linux going forward, simply execute

wsl

Typescript interfaces

Interfaces (within Typescript) are used in a variety of ways.

Defining expectations/restrictions

We can define an interface such as IPoint

interface IPoint {
    x: number;
    y: number;
}

Just like other languages, we can then implement this interface and we’re required to duplicate the properties or methods declared on it.

For example here’s an implementation

class Point implements IPoint {
    constructor(public x: number, public y: number) {        
    }
}

We’ve used public constructor parameters hence implementing the IPoint interface.

Now we can create an instance of the Point like this

// p is a Point
var p = new Point(2, 3);
// p is declared as an IPoint
var p: IPoint = new Point(2, 3);

Within TypeScript an interface can also simply be thought of as shaping our data, so in this example we could create an anonymous class of type IPoint like this

var p: IPoint = {x : 2, y: 4};

We can also declare an instance of an anonymous type like this

var p = {x : 2, y: 4};

Typescript supports “duck typing” so we can create functions such as

function output(p: IPoint) {
   //
}

and we can pass a type which implements an IPoint or a duck typed anonymous type, for example

output({x : 2, y: 4});

Because of duck typing we do have an issue whereby the following two interfaces are structurally equivalent

interface IPoint {
    x: number;
    y: number;
}

interface I2d {
    x: number;
    y: number;
}

and hence this will compile and run

var i2d: I2d = {x : 2, y: 4};
var p: IPoint = i2d;

In such a case, the interfaces have the same properties and names and are structurally equivalent.

Things get a little more interesting with interfaces and anonymous types, in that we can write something like this

function whatIsThis() {
    return {x:2};
}

Obviously it’s not an IPoint or I2d, but it could be. In this example it’d create an anonymous type but we could cast the type like this, but this will fail to compile due to the missing y property.

function whatIsThis() {
    return <IPoint>{x:2};
}

Empty interfaces

We can also define empty interfaces, such as

interface IEmpty {}

function output(e: IEmpty) {
    console.log(e);
}

output("Hello World");

In this case this is equivalent to an any and hence does not cause a compile time error and output will display “Hello World”.

Type erasure

Interfaces within Typescript are erased at compile/transpile time, hence whilst they aid in ensuring our types are as expected, once compiled to JavaScript they’re removed.

Hence no runtime type checking exists for such types.

Listing environment variables

Occasionally we might wish to see a list of all the current environment variables.

Windows

In Windows, from the command prompt, execute

set | more 

or from Powershell

Get-ChildItem Env:

Linux

Within Linux, from the shell, execute

printenv

TypeScript constructor parameter properties

TypeScript offers a short-cut to creating properties/fields from the parameters declared on the constructor.

For example, if we declare our class and constructor like this

class Person {
    constructor(name: string, age: number) {
    }
}

let p = new Person("Scooby", 10);
p.name = "Doo";

The TypeScript transpiler will display the error “Property ‘name’ does not exist on type ‘Person'” and obviously the parameters name and age will not exist within the Person class as they’ve not been declared.

However if we prefix the parameters with either public, private, protected or readonly then TypeScript generates properties on the Person object automatically for us.

protected parameter properties

As you’d probably expect, with the accessor of protected properties are generated which are visible to the Person object and any subclass of the Person.

For example

class Person {
    constructor(protected name: string, protected age: number) {
    }
}

When we run this through the transpiler we get the following

var Person = /** @class */ (function () {
    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    return Person;
}());

If we attempt to access the properties name and age from outside the class (using TypeScript) then we’ll get the error “Property ‘name’ is protected and only accessible within class ‘Person’ and its subclasses.”.

private parameter properties

If we now change the accessors to private, for example

class Person {
    constructor(private name: string, private age: number) {
    }
}

The transpiler will, again, create the same output as the previous JavaScript code, but the generated properties, from the TypeScript point of view, are only accessible from the Person class. Trying to access them from outside of the Person class will result in the following error, “Property ‘name’ is private and only accessible within class ‘Person’..

public parameter properties

Changing the accessors to public will, as you probably expected, create public properties/fields which are accessible outside of the Person class, here’s the altered source code.

class Person {
    constructor(public name: string, public age: number) {
    }
}

Ofcourse, the JavaScript code is unchanged.

readonly parameter properties

Finally, if we now change the accessors to readonly, for example

class Person {
    constructor(readonly name: string, readonly age: number) {
    }
}

The transpiler will generate, what appears to be, getters only. Hence trying to interact with these properties outside of the class will result in the following error “Cannot assign to ‘name’ because it is a read-only property.”

Whilst JavaScript can support the concept of readonly properties, the transpiler does not go this route (shown below)

Readonly properties in JavaScript

If we take the code generated by the transpiler, we could add the following

Object.defineProperty(Person.prototype, "name", {
    value: "name",
    writable: false
});

and when run (assuming we try to assign a value to name), we’ll get the following error “Cannot assign to read only property ‘name’ of object ‘#‘”.

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.