Create a Block in Typescript

Created: In WordPress

I’ve been reading and learning Typescript recently, and I quite like it. The added type safety is a great feature to help create more error-free and stable code. You can read more about Typescript here.

This got me thinking that it should be possible to create a WordPress Block in Typescript, which of course it is.

For the impatient, the stubbed repo: https://github.com/mkaz/tsblock

Build & Config

The block setup uses the same wp-scripts config from @wordpress/scripts package and extends webpack adding the ts-loader and resolver for the appropriate extensions.

Block Adjustments

Typescript + React

Typescript works with React fine, see the Typescript JSX documentation for details. The biggest change is likely adding types for your properties, here is an example for the src/edit.tsx

import * as React from 'react';
import { __ } from '@wordpress/i18n';

type EditProps = {
	"className": string,
};

const Edit = ( { className }: EditProps ) => {
	return (
		<p className={ className }>
			{ __( 'Hi from the editor!', 'tsblock' ) }
		</p>
	);
}

export default Edit;

WordPress Packages

Depending on the packages you use for your block, you may need to add additional type support. The following was done to add types for the @wordpress/blocks package used.

$ yarn add @types/wordpress__blocks

For example, if your block uses components from @wordpress/components you will need to add the necessary types. Use:

$ yarn add @types/wordpress__components

Summary

To get started, you can clone the repo (or copy the configs) from: https://github.com/mkaz/tsblock

There really isn’t too much difference in developing blocks in Typescript. Writing in Typescript might take a bit longer, since you need to be more explicit with your functions and parameters. However, this is what provides the type safety to catch potential bugs. For example, are all those required parameters passed in? Do parameter names and types match? Etc…

It is much nicer to catch bugs in the compile step during development, then by users in production.

Thanks to @beau.collins.pub for the assist.

Leave a Reply