Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

54
Views
How do I spread an object (class instance properties) to the parent's super constructor?

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
    );
  }
}
7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.