"Exploring the versatility of TypeScript's union types in that particular situation

Hey there! I'm working on a function within a Point class that adds up the values of X and Y with either Point or individual X and Y parameters.

For example:

public Offset(dx: number, dy: number) {
    this.X += dx;
    this.Y += dy;
}

public OffsetPoint(p: Point) {
    this.X += p.X;
    this.Y += p.Y;
}

I was wondering if it's possible to consolidate these two functions into one in TypeScript instead of having separate ones?

Answer №1

In my opinion, there is no definitive right way to approach this problem. However, I have stumbled upon a clever workaround:

class Point {
    X: number
    Y: number

    constructor(X: number, Y: number) {
        this.X = X;
        this.Y = Y;
    }

    public Offset(dx : number | Point , dy? : number) {
        if (dy) {
          this.X += dx as number;
          this.Y += dy as number;
        } else {
          let p = dx as Point;
          this.X += p.X;
          this.Y += p.Y;
        }
    }
}

let a = new Point(1, 1);
let b = new Point(2, 2)

console.log('a.x', a.X, 'a.y', a.Y); // "a.x",  1,  "a.y",  1 
a.Offset(b)
console.log('a.x', a.X, 'a.y', a.Y); // "a.x",  3,  "a.y",  3 
a.Offset(10, 20)
console.log('a.x', a.X, 'a.y', a.Y); // "a.x",  13,  "a.y",  23 

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

Converting intricate JSON objects into a class using Typescript and Angular 5

I am attempting to transform a complex JSON response object (received from my Node.js/Mongoose backend) into a TypeScript class that contains multiple type classes. A Moment class includes an author of type User and a comments array of type Comment. mome ...

Struggling to grasp React class components while working with generics

I'm having trouble understanding how this is supposed to function. I have a parent class with props and an interface for the child class's props. The issue arises with a TypeScript error message: The property 'lineWidth' does not exist ...

Using Angular 2 to assign a pipe dynamically from a variable

Could something like the following be achievable: {{property | some_variable_name}} I am aiming to utilize a pipe that is defined in a JSON configuration (or variable), but I am uncertain if it is feasible to include the pipe name within the interpolatio ...

The specified type '{ flag: boolean; }' cannot be assigned to the type 'IntrinsicAttributes & boolean'

Just delving into TypeScript and I've hit a snag when trying to pass an element to another component. Feeling lost on how to proceed. Error lurking in Cards component export default function MySpecialProject() { const [toggle, setToggle] = useState ...

Identifying data types in arrays using TypeScript type predicates

My current approach involves a function that validates if a variable is an object and not null: function isRecord(input: any): input is Record<string, any> { return input !== null && typeof input === 'object'; } This type predica ...

Invoke React hook based on Promise conditions

I am facing a dilemma where I need to make a server request based on an ID stored in AsyncStorage. This is the setup I have been thinking about: AsyncStorage.getID().then(id => { useLoadFromServer(id) } However, I keep running into errors related t ...

Is there a way to inform TypeScript that an object can only return properties from values found within an array?

I am trying to ensure that the return object from a function in TypeScript only allows keys that correspond to string values present in an array passed as an argument to the function. The returned object should contain a subset of keys from a list of valid ...

Angular 2's JSON tube is malfunctioning

Each time I attempt to utilize the JSON pipe to pass my data, an error message appears in the console: Unhandled Promise rejection: Template parse errors: The pipe 'json' could not be found (... Can someone help me understand what mistake I am ...

When a checkbox is clicked, how can we use Angular 4 to automatically mark all preceding checkboxes as checked?

I have a series of checkboxes with labels such as (Beginner, Intermediate, Advanced, Expert, etc.). When I click on any checkbox, I want all previous checkboxes to be checked. For example: If I click on Advanced, only the preceding checkboxes should get ...

Error: Trying to access a property that does not exist (postgresClient) on an undefined variable

For my latest project, I've been working on creating an API that utilizes PostgreSQL to store shortened links. However, I keep encountering the issue where postgreClient is consistently undefined when attempting to run a query to the database. In my ...

Field types: Elements encased within square brackets

When using Flow Types: export type GroupType = { options: OptionsType, [string]: any, }; What does the syntax [string]: any signify? Edit : Appreciate all the responses provided. How should I interpret this particular piece of code? import type { ...

What is the best way to determine the type of the three values using TypeScript interfaces?

Often, the code breaks due to incorrect types for label, description, details. To ensure proper arguments are provided: label should be a string. description should be either a string or an array of strings. details should be a string. As a TypeScript ...

Protractor can be quite tricky as it tends to throw off errors in the first it block, causing

After writing a protractor test for an Angular application with a non-angular login page, I decided to include the login process in a separate file using browser.waitForAngularEnabled(false);. I then created a describe block with a series of it blocks to ...

The issue of saving Rails input from an Angular2 front end has been causing some trouble

Currently, I am in the process of developing a front-end application using Angular 2 that retrieves data from a Rails 5 API. This specific application serves as a network inventory tool. One particular feature of this app is an Asset-form in Angular2 whic ...

TypeError: describe is not a function in the Mocha testing framework

Encountering an issue with mocha-typescript throwing an error indicating that describe is not defined. TypeError: mocha_typescript_1.describe is not a function at DatabaseTest.WrongPath (test/database_test.ts:21:9) at Context.<anonymous> ...

There has been an unhandled runtime error: [object ProgressEvent] occurring with Next.js/Typescript

Exploring the world of nextJS and typescript is new to me. I am currently working on creating a simple blog using nextJS/typescript with a sanity CMS backend. Everything seems to be running smoothly during development, but then I encounter this Unhandled R ...

Can the typography style of a material-ui TextField component be modified to incorporate a caption variant?

Currently diving into the world of material-ui for implementation in a Typescript React setup. Utilizing the code snippet below in a Dialog: ... <React.Fragment> <Typography variant="body1"> <Box mt={1}>Heading</Box> & ...

What is the function of the OmitThisParameter in TypeScript when referencing ES5 definitions?

I came across this specific type in the ES5 definitions for TypeScript and was intrigued by its purpose as the description provided seemed quite vague. /** * Removes the 'this' parameter from a function type. */ type OmitThisParameter<T> ...

Problem with spacing on the x-axis in the NGX-Charts bubble chart

In my Angular project, I am utilizing the ngx-charts bubble chart to illustrate events on a timeline. The chart content dynamically updates as users narrow down a specific time range. Although I am straying slightly from the intended use of the bubble cha ...

When `Omit` is applied to a type that includes an index signature, it removes all field declarations that are not part of

Currently, I am working on developing a React component that wraps around the Select component from react-select. The issue arises with a specific prop declaration that can be seen here: export type SelectComponentsProps = { [key in string]: any }; expor ...