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?
CustomArray extends Array?CustomArray extends Arraywill allow the instancesCustomArrayaccess all the functionalities of Array. That's not your issue here. Are you using react or something similar where thevalueparameter being passed is immutable? Like this: Object is not extensible error when creating new attribute for array of objects