Type safe way of adding material plugins?

Typescript complains Property 'blackandwhite' does not exist on type 'Material' when trying to add a material plugin e.g.

BABYLON.RegisterMaterialPlugin("BlackAndWhite", (material) => {
  material.blackandwhite = new BlackAndWhitePluginMaterial(material);
  return material.blackandwhite;
});

What’s the best type safe way to do this or should I just use // @ts-ignore for those lines?

You can use (material as any).blackandwhite = ... or (material as MyMaterialWithBW).blackandwhite if you create a MyMaterialWithBW class that subclasses Material and which is adding a proper blackandwhite property. I think the latter way is better because later on you can access directly material.blackandwhite instead of doing (material as any).blackandwhite each time you want to get access to the plugin.

Note you can also retrieve a plugin from a material by doing material.pluginManager.getPlugin(pluginName), so technically you could simply do:

BABYLON.RegisterMaterialPlugin("BlackAndWhite", (material) => {
  new BlackAndWhitePluginMaterial(material);
  return null;
});

which will avoid the error with typescript.

3 Likes

Thanks @Evgeni_Popov . Makes sense.