SPFx: Extending the Object/Array via Object|Array.prototype destroys some SharePoint functionality

I am Sergej and I am a Software Architect from Germany (AURUM GmbH). I have been developing on Microsoft technologies for more than 14 years, especially in SharePoint / Microsoft 365. With this blog, I want to share my knowledge with you and also improve my English skills. The posts are not only about SPFx (SharePoint Framework) but also about tips & tricks around the M365 world & developments of all kinds. The posts are about TypeScript, C#, Node.js, Vue.js, Visual Studio/ VS Code, Quasar, PowerShell, and much more. I hope you will find some interesting posts. I would also be happy if you follow me. Greetings from Germany Sergej / $€®¥09@
Yesterday a customer told me that when clicking on "Settings (gear icon)" ==> "Site permissions" the panel that opens afterward does not show any permissions. Well, what should/can I do there? After all, this is a standard function! But the error comes only if one of the webparts was placed, which I developed.
In the picture below you can see how this should look like:

And this is how it looks when the custom web part is placed

Additionally, there are the following errors in the console The expression "web/SiteGroups/GetById(id=undefined)" is not valid.:

Finding the cause was really not easy. I had to comment in/out the code line by line. But in the end I found the cause. It was my npm package "@spfxappdev/utility"
To be more precise, it was the array object extensions. The code looked (shortened) like this:
declare global {
interface Array<T> {
FirstOrDefault(predicateFunc: (item: T) => boolean, defaultValue?: T|null): T|null;
}
Array.prototype.FirstOrDefault = function(...)
I found out that as soon as you use Object.prototype.myFunc or Array.prototype.myFunc, the error listed above appears (maybe even more). Even this code (quick and dirty, used for testing purposes) causes this error:
(Array as any).prototype.test = null;
With String.prototype, for example, there are no problems. You can fix the error by replacing Array.prototype.myFunc = function() with...Object.defineProperty
if(typeof Array.prototype.FirstOrDefault === "undefined") {
Object.defineProperty(Array.prototype, 'FirstOrDefault', {
value: function<T>(this: T[], predicateFunc: (item: T) => boolean, defaultValue: T|null = null): T|null {
//Code
}
});
}
There are no problems with this type of object extension definition.
I have updated both my npm package "@spfxappdev/utility" and "@spfxappdev/framework". I recommend everyone who uses these packages (or parts of the code of my array extensions) to update the packages or update the code if needed.
Sorry for this mistake. And all who have this error without using my packages, I hope this post has helped you.






