Skip to content

Instantly share code, notes, and snippets.

@adamziel
Created February 22, 2022 13:52
Show Gist options
  • Save adamziel/ec41157c10ac11286609a635adb35a0b to your computer and use it in GitHub Desktop.
Save adamziel/ec41157c10ac11286609a635adb35a0b to your computer and use it in GitHub Desktop.

Extending

You can extend the entity record definitions using TypeScript's declaration merging.

For example, if you're building a plugin that displays a number of views of each comment, you can add a new numberOfViews field to the Comment type like this:

// In core-data
export namespace WPBaseTypes {
	// This is the parent interface – it can be extended
	export interface Comment< C extends Context > {
		id: number;
		// ...
	}
}

// This the child type used in function signatures – it cannot be extended
export type Comment< C extends Context > = OmitNevers<
	WPBaseTypes.Comment< C >
>;

// In the plugin
import type { Context } from '@wordpress/core-data';
// Target the core-data module
declare module '@wordpress/core-data' {
	// Extend the WPBaseTypes namespace through declaration merging
	export namespace WPBaseTypes {
		// Extend the parent Commet interface through declaration merging
		export interface Comment< C extends Context > {
			numberOfViews: number;
		}
	}
}

import type { Comment } from '@wordpress/core-data';
// Create an instance of the child type
const c : Comment< 'view' > = ...;

// Extending the parent had the desired effect on the child type:
// c.numberOfViews is a number
// c.id is still present

Of course, you will also need to extend the REST API to expose the numberOfViews property.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment