Moving to Typescript with React

Typescript gives you a number of nice little statically typed features, which Javascript is sadly lacking. However, looking online, most of the tutorials and references use Javascript. This is a handy little post to allow you (or me) to use Typescript; or to use Javascript, and then transition to Typescript. Since you can use both in your project, you might find that migrating files one at a time allow you to gradually transition your code-base.

File name

When you create your first React app, you get a, by now, pretty standard SPA app. The entire app is running Javascript. To change one of the files over to Typescript, simply change the extension:

You now have your first Typescript component… Now the errors begin!

Props

Parameter ‘props’ implicitly has an ‘any’ type, but a better type may be inferred from usage.ts(7044)

This warning appears when you have the following constructor:

constructor(props) {  

Now that you’ve moved from a dynamic to a statically* typed language, Typescript is simply suggesting that you may have a better type than the Any** type that is assigned by default.

The easiest, and best transition here is simply to tell Typescript the type; for example:

interface IProps {
}

export class Home extends Component<IProps> {

  constructor(props: IProps) {    

If you actually have any properties, then you’ll need to include them in your interface; for example:

interface IProps {
  myValue: boolean
}

State

In Javascript, you define state by usage in the constructor; for example:

export class FetchData extends Component {
  static displayName = FetchData.name;
  constructor(props) {
    super(props);
    this.state = { forecasts: [], loading: true };
  }

Again, you need to define what the structure of state is:

interface IState {
  forecasts: string[];
  loading: boolean;
}

Then, you can reference that in the constructor, and pass the type into the base component:

export class Home extends Component<IProps, IState> {

  constructor(props: IProps, ) {    
    super(props);
    this.state = { 
      forecasts: [], 
      loading: true 
    };
  }

External Interface Files

One of the consequences of declaring these interfaces, is that you’ll quickly find that you need to reference the same interface from more than one place. For example, you may read some data in one component, and then display it in another. You could simply redeclare the interface in both places, but that feels dirty.

To get around this, you can simply declare a set of interfaces in a single file, or set of files. In C#, I would declare a single interface per file, so I’m tempted to lean towards this approach:

This doesn’t necessarily apply to any interfaces that are relevant to only a single component (for example, the interface for the props – unless they are shared – feels like it’s perfectly happy in the same file as the component).

Raising Events

In the same way as you now have to define what props look like, when you raise an event, you need to define what the event looks like; that is, you must tell Typescript the event type that you’re handling.

interface SearchProps {
    searchText: string;
    searchAction: (e: React.MouseEvent<HTMLButtonElement>) => void;
}
function Search(props: SearchProps) {
    
    return (
        <div>
            <label>Search</label>
            <textarea>{props.searchText}</textarea>
            <button onClick={props.searchAction}>Search</button>
        </div>
    );
}
export default Search;

External Libraries

If you’re referencing an external library, you may not have the Typescript definitions; let’s take reactstrap for example:

Could not find a declaration file for module ‘reactstrap’. ‘c:/myproject/ClientApp/node_modules/reactstrap/dist/reactstrap.cjs.js’ implicitly has an ‘any’ type.

Try `npm install @types/reactstrap` if it exists or add a new declaration (.d.ts) file containing `declare module ‘reactstrap’;`ts(7016)

You should be able to simply install this – which, in fact, it tells you to do in the error message:

npm install @types/reactstrap

References

https://stackoverflow.com/questions/46987816/using-state-in-react-with-typescript/46987987

Notes

* I’m not convinced that Typescript qualifies as a true statically typed language, rather it provides static typing for a dynamically typed language.

** Any is Typescript’s way of allowing you to revert to JavaScript, and just not type a specific variable; this is why I have doubts as to whether Typescript can be considered statically typed.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.