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

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

$€®¥09@'s photo
$€®¥09@
·Jan 14, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

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:

How the panel should look

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

How the panel looks

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

Errors in the console

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.

Did you find this article valuable?

Support $€®¥09@ by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this