Is it possible to pass values to an object of an extended class?

Uncertainty creeps in as I ponder a potentially foolish idea (possibly recursive): I find myself tasked with building two objects using the same parameters. One object features a shared method, while the other boasts two private methods (think of them as polygons - one serving as a fixed background, and the other positioned on top as a "progressArc," requiring more complex calculations).

My current approach for creating this combined instance looks like this:

const createExergon = (radius = 100, points = 5, strokeWidth = 0, progress = 50) => {

    // Method: calcPoints
    let backgr = new PolygonBG(radius, points, strokeWidth);
    
    // Methods: calcPoints (inherited), length, gradient
    let progr = new PolygonPG(radius, points, strokeWidth, progress);
    return { backgr, progr }
};
let exergon = createExergon();

I am now considering the possibility of running calcPoints() just once to share the values instead of the method...

(apologies, it appears the tags have been tampered with, but rest assured, this is indeed TypeScript)

EDIT: This is the current structure I have (as a newcomer to TypeScript classes, it might not be the most elegant approach...)

class Point {
    x: number;
    y: number;
    constructor(x = 0, y = 0) {
        this.x = x;
        this.y = y;
    }
};

interface Poly {
    radius: number;
    points: number;
    strokeWidth: number;
    readonly coords: Point[];
    readonly length?: number;
    readonly gradient?: number[];
}

//TODO: Find a way to pass default values
let defValues = { radius: 100, points: 5, strokeWidth: 0 };

// Creates a static Polygon (either standalone or serving as background for progressPolygon)
class PolygonBG implements Poly {
    radius: number;
    points: number;
    strokeWidth: number;
    readonly coords: Point[];

    constructor(radius=100, points=5,strokeWidth=0) {
        this.radius = radius;
        this.points = points;
        this.strokeWidth = strokeWidth;
        this.coords = this.calcPoints();
    }
    /**
     * 
     * @returns points of the regular polygon with the given attributes
     */
    calcPoints() {
        let p: Point[] = []
        ...

        };
        return p;
    };
};

// Creates a polygon for progress calculation
class PolygonPG extends PolygonBG {
    progress: number;
    readonly length: number;
    readonly gradient: number[];

    constructor(radius = 100, points = 5, strokeWidth = 0, progress = 50) {
        
        super(radius, points, strokeWidth);
        this.length = this.len();
        this.gradient = this.grad();
        this.progress = progress;
        
    }; 
    
    private len(): number {
        // Here, we require this.coords from calcPoints()
        ...
        return l;
        
    };
    
    private grad() {
        let g: number[] = [];
        for (let i: number = 0; i < this.points; i++) {
        // Here, we need this.coords from calcPoints()
        ...
        }
        return g;
    };
    
};
// Created here with default values for simplicity
const createExergon = () => {
    let backgr = new PolygonBG();
    let progr = new PolygonPG();
    return { backgr, progr }
};
let exergon = createExergon();

So currently, calcPoints() is executed twice (with the same parameters resulting in the same output but creating two distinct objects), which is functional but not the cleanest solution. It seems there is a fundamental logic issue that eludes me.

(my apologies for the influx of messages. I'm hopeful someone can offer a breakthrough idea.)

Answer №1

After some consideration, I've decided to transfer the output of calcPoints() as parameters from PolygonBG to PolygonPG.coords. Check out this TypeScript utility type for reference: TS Partial<Type>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Please indicate the data type in Vue using Typescript

I'm currently struggling with Vue (3) + Typescript while attempting to specify a data property with a specific type. I have created a .d.ts file, but unfortunately, it hasn't helped. This is what I'm trying: import Modeler from 'bpmn-js ...

What could be causing this TypeScript code to not pass typechecking?

defining two objects in TypeScript with different property sets and assigning them to each other. Link to more information ...

Ways to reveal heavily nested components when the Angular change detector fails to detect them

A particular component called Grid has been implemented with the following template: <div *ngFor="let row of item.rows"> <div *ngFor="let col of row.cols"> <div *ngFor="let grid of col.items"> < ...

Importing a file using its absolute path in JavaScript

Within the dependencies directory, there exists a module named foo: import foo from '../dependencies/foo'; // This import statement works as intended The challenge arises when attempting to import from a different path due to deployment in an AW ...

The challenge with the Optional Chaining operator in Typescript 3.7@beta

When attempting to utilize the Typescript optional chaining operator, I encountered the following exception: index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access. Here is my sample code: const ...

I'm having trouble with the calculator, unable to identify the issue (Typescript)

I'm struggling with programming a calculator for my class. I followed the instructions from our lesson, but it's not functioning properly and I can't pinpoint the issue. I just need a hint on where the problem might be located. The calculat ...

Deno.Command uses backslashes instead of quotes for input containment

await new Deno.Command('cmd', { args: [ '/c', 'start', `https://accounts.spotify.com/authorize?${new URLSearchParams({ client_id, response_type: 'code', ...

What is the key to mastering any concept in Angular2 for optimal results?

When creating a Pipe to filter data, I often use the datatype any, allowing for flexibility with types. However, I have some questions regarding this approach: Is it considered a best practice? Does it impact performance when handling large amounts of da ...

In order to use the serve command, it is necessary to run it within an Angular project. However, if a project definition cannot be located

An error occurred while running the ng serve command: C:\Mysystem\Programs\myfwms>ng serve The serve command needs to be executed within an Angular project, but a project definition could not be found. I encounter this error when ...

Are Named Capture Groups in Typescript Regex malfunctioning?

Update: I have included @babel/plugin-transform-named-capturing-groups-regex, following the suggestion from @Jack Misteli to explore Babel. Update:: Utilizing https://babeljs.io/en/repl#?browsers=defaults%2C%20not%20ie%2011%2C%20not%20ie_mob%2011&buil ...

node-ts displays an error message stating, "Unable to locate the name '__DEV__' (TS2304)."

I recently inserted __DEBUG__ into a TypeScript file within my NodeJS project. Interestingly, in VSCode, no error is displayed. However, upon running the project, I encounter an immediate error: error TS2304: Cannot find name '__DEBUG__'. I att ...

Discover the Prisma findMany method for implementing tanstack react table functionality

I'm looking to build a table (using tanstack table) populated with data fetched from Prisma.findMany. Let's suppose I have a User model: model User { id Int @id @default(autoincrement()) name String age String email String } Now, in my p ...

Retrieve data upon component mounting and deactivate the query in React-query

When navigating to a search result page, query parameters are passed to useQuery. I want the data to be fetched only when the user clicks the "Search" button after changing the search prompt. I attempted to use enabled: false and call refetch() on button ...

Utilizing a directive in contexts beyond a component

I have developed a popover module that consists of two components and three directives. However, I am encountering an issue where I am unable to utilize the directives outside of the main component. Whenever I try to do so, I face an editor error stating: ...

Solving issues with event handling through addEventListener within a functional component in React

I am working on a React component that includes an input field and I want to implement a character autocompletion feature. The idea is that when a user types " or ', the same character should be automatically added again, with the cursor placed i ...

Steps for connecting to a property in another component

As a newcomer to Angular, I am exploring new concepts for the first time. I have a custom component called Timeselector with an Apply button whose enable/disable state is determined by validations performed in another custom component called Monthpicker. C ...

Compiling Typescript with module imports

In my project, I am working with two files named a.ts and b.ts. The interesting part is that file b exports something for file a to use. While the TypeScript compiler handles this setup perfectly, it fails to generate valid output for a browser environment ...

What steps can I take to guarantee that the observer receives the latest value immediately upon subscribing?

In my Angular 2 and Typescript project, I am utilizing rxjs. The goal is to share a common web-resource (referred to as a "project" in the app) among multiple components. To achieve this, I implemented a service that provides an observable to be shared by ...

Stopping HTTP client calls in OnDestroy hook of an Angular Service

Is it possible to automatically unsubscribe from an http call in an Angular service using the ngOnDestroy hook? Just to note, I am already familiar with using the rxjs 'take' operator or manually unsubscribing from the service within the compone ...

What is the reason behind the absence of compile time errors when using 'string' functions on an 'any' field type variable in TypeScript?

Looking at the following typescript code snippet: let a; a = "number"; let t = a.endsWith('r'); console.log(t); It is worth noting that since variable 'a' is not declared with a specific type, the compiler infers it as ...