I was introducing typescript to my current code. The size of the codebase is quite huge so started from the basic types. I have built custom data types to handle UI in a better way.
Following is the code for CustomArray
which I have.
/**
Author - Harkirat Saluja
Git - https://bitbucket.org/salujaharkirat/
**/
declare global {
interface Array<T>{
filterBy(o: T): Array<T>,
sortAscBy(o: T): Array<T>,
sortDescBy(o: T): Array<T>
}
}
class CustomArray {
static init (value = []) {
if (!value) {
value = [];
}
if (!(value instanceof Array)) {
value = [value];
}
value.filterBy = function (property) {
return !property ? this : this.filter(item => item[property]);
};
value.sortAscBy = function (property) {
return !property ? this : this.sort((a, b) => a[property] - b[property]);
};
value.sortDescBy = function (property) {
return !property ? this : this.sort((a, b) => b[property] - a[property]);
};
return arrayValue;
}
}
export default CustomArray;
In production I am getting error TypeError: Cannot add property to a non extensible object
.
As per the mozilla documentation, if we add Object.preventExtensions
it should show me this error but I am not using that anywhere.
I was debugging it a bit and following code works fine:-
/**
Author - Harkirat Saluja
Git - https://bitbucket.org/salujaharkirat/
**/
declare global {
interface Array<T>{
filterBy(o: T): Array<T>,
sortAscBy(o: T): Array<T>,
sortDescBy(o: T): Array<T>
}
}
class CustomArray {
static init (value = []) {
if (!value) {
value = [];
}
if (!(value instanceof Array)) {
value = [value];
}
const arrayValue = [...value]; //Making a new copy works
arrayValue.filterBy = function (property) {
return !property ? this : this.filter(item => item[property]);
};
arrayValue.sortAscBy = function (property) {
return !property ? this : this.sort((a, b) => a[property] - b[property]);
};
arrayValue.sortDescBy = function (property) {
return !property ? this : this.sort((a, b) => b[property] - a[property]);
};
return arrayValue;
}
}
export default CustomArray;
Though the error is fixed, it will really me if someone is able to help me understand why I am facing this issue?