How can I spread a class properties to the parent's super constructor?
ActionLog is a base class, it's instantiated in a method inside ActionRequestAccess
ActionRequestAccess.ts
export class ActionRequestAccess extends ActionLog {
constructor(public actionLog: ActionLog, public customerId: string) {
super(
actionLog.id, // Want to get rid of these assignments <<< and switch to something like: ...actionLog
actionLog.type,
actionLog.date,
actionLog.address,
actionLog.location
);
}
static override fromMap(map: any) {
if (!map) {
return null;
}
const baseMap = super.fromMap(map);
if (!baseMap) {
return null;
}
return new ActionRequestAccess(baseMap, map['customerId'] ?? null);
}
}
ActionLog.ts
import { ActionType } from '../../enums';
export class ActionLog {
constructor(
public id: string,
public type: ActionType,
public date: Date,
public address: string,
public location: string
) {}
static fromMap(map: any) {
if (!map) {
return null;
}
return new ActionLog(
map['id'] ?? null,
map['type'] ?? null,
map['date'] ?? null,
map['address'] ?? null,
map['location'] ?? null
);
}
}
You can use Object.values
on the object inside ActionRequestAccess
.
constructor(public actionLog: ActionLog, public customerId: string) {
super(...Object.values(actionLog));
}
But this means that the order the values of your object are passed to the function mathers, so this pattern is a little bit unsafe. This will work
const myObject = new ActionRequestAccess({
id: 1,
type: 'myType',
date: 'myDate',
adress: 'myAdress',
location: 'myLocation',
});
but this will switch the position of the id and type and will not work.
const myObject = new ActionRequestAccess({
type: 'myType',
id: 1,
date: 'myDate',
adress: 'myAdress',
location: 'myLocation',
});
If you can change the expected value to the constructor of ActionLog
to be an object instead of parameters, then that will probably be easier and more safe.