I have a variety of object types that I need to manipulate within an array consisting of those object types.
type AB = { a:number, b:number}
type CD = { c:number, d:string}
type DE = { d:number, e:boolean}
let state: AB[] = []
function onStateChange(newState: AB[]) {
console.log(newState)
state = newState
}
function add(blank: AB ) {
onStateChange([
...state,
blank,
]);
}
function remove(index: number) {
onStateChange([...state.slice(0, index), ...state.slice(index + 1)]);
}
function update(index: number, updated: Partial<AB>) {
onStateChange([...state.slice(0, index),
{ ...state[index], ...updated},
...state.slice(index + 1)]);
}
To achieve this goal with the add
, remove
, and update
methods applied to state
, I am exploring ways to include additional methods that result in modified copies of the original data
interface WithListManagement<T> {
withAdd(blank: T ) : T[] {
return [
...state,
blank,
]);
}
withRemove(index: number) {
return [...state.slice(0, index), ...state.slice(index + 1)]);
}
withUpdate(index: number, updated: Partial<AB>) {
return [...state.slice(0, index),
{ ...state[index], ...updated},
...state.slice(index + 1)]);
}
}
Thus, something like this approach can be implemented:
let state: WithListManagement<CD> = []
function add(blank: CD ) {
onStateChange(state.withAdd({c:1, d:'foo'});
}
Note that my objective is to avoid altering the Array prototype as I specifically intend for these modifications to be targeted towards specific lists rather than all arrays.
UPDATE regarding context.
The primary aim is to create functionality akin to default interface methods
in Java while also considering type erasure in TypeScript.
For instance, if we take the type AB[]
, which inherently possesses standard Array
methods such as map and length, along with functionalities like JSON.stringify().
I envision having an interface
or potentially a class
that provides capabilities similar to WithListManagement<AB>
, possessing the same behavior as AB[]
but inclusive of the supplementary methods outlined above.