Ways to inform TypeScript about my custom extension for Object.defineProperty()

Currently, I am working on a Canvas using the Konva library and found that I needed to add an extension to the Konva.Line prototype. This was necessary because when using getAbsolutePosition(), you only receive relative y values of Lines:

Object.defineProperty(Konva.Line.prototype, "absY", {
    value: function()  {
        return this.getSelfRect().y + this.y()
    },
    writable: true,
    configurable: true,
});

Although this code functions correctly, in my IDE (WebStorm), the ".absY()" call always appears red because TypeScript is not aware of this type.

How can I resolve this issue within a SvelteKit Project?

I understand that this may not be considered good practice, but I have become accustomed to Kotlin πŸ˜…

I have already attempted to include

declare namespace Konva {
    interface Line {
        absY: () => number;
    }
}

in the app.d.ts file, however this did not provide a solution and the IDE still shows "Unused interface Line"

Answer β„–1

In order to make the necessary changes, you must update the definition where it is currently specified
https://tsplay.dev/m3Vl1N

declare module "konva/lib/shapes/Line.js" {
  export interface Line {
    foo: "bar"
  }
}

import Konva from "konva"
let line = new Konva.Line()
let bar = line.foo
//  ^?
// let bar: "bar"

It is important to note that export default namespace cannot be altered. This task may not be feasible if this particular interface is not being exported elsewhere.

Answer β„–2

If you're looking to customize the behavior of the Konva Line class, consider extending it with your own properties.

import Konva from 'konva';

// extend the Konva `Line` class
class MyCustomKonvaLine extends Konva.Line {
    public absY() {
        return this.getSelfRect().y + this.y()
    }
}

// example usage
const greenLine = new MyCustomKonvaLine({
    points: [5, 70, 140, 23, 250, 60, 300, 20],
    stroke: 'green',
    strokeWidth: 2,
    lineJoin: 'round',
    dash: [33, 10]
});

// output the absY value
console.log('greenLine absY equals:', greenLine.absY());

const stage = new Konva.Stage({
    container: 'container',
    width: window.innerWidth,
    height: window.innerHeight,
});

const layer = new Konva.Layer();

layer.add(greenLine);
stage.add(layer);

I have no experience with Svelte or Konva.

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

Using React for passing data

In the snippet found in "CameraPage.tsx", there is a logical function that is responsible for fetching camera images. This function simply makes a GET request to search for images stored in the backend, which will later be displayed on the FrontEnd. The op ...

Deleting an element from an object in TypeScript

Is there a way in TypeScript to exclude certain elements (e.g. 'id') from an object that contains them? ...

What is the proper way to indicate that a function parameter corresponds to one of an Interface's keys?

When working with TypeScript, I am looking for a way to validate that the argument passed to myFunction matches one of the keys defined in MyInterface. Essentially, I want to enforce type checking on the arg parameter as shown below. export interface MyInt ...

Retrieve an additional 10 items from the API when the button in the Angular list is clicked

I need to display 10 items each time the button is clicked. Below is the code snippet for the services: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http' @Injectable({ providedIn: ' ...

Encountering Syntax Error while running `ionic serve` in IONIC2

I'm stuck on this Syntax error and I can't figure out what went wrong. It keeps showing up even though I copied the code directly from the official ionic2 docs. SyntaxError: D:/Manson/Arts/Ionic/IonicTodo2/app/pages/list/list.js: Unexpected toke ...

Ways to convert an asynchronous operation to synchronous in JavaScript

Currently in the process of developing an eslint plugin, I have come across a particular issue. My goal is to implement real-time changes to the configuration file by making an HTTP request to retrieve the JSON configuration. When attempting to execute co ...

Adjust the dimensions of the ng2-charts to fit your needs

Is there a way to specify the width and height of a chart using ng2-charts? Specifically, I am working on a Bar chart similar to the one shown in the ng2-charts demo. public doughnutChartLabels:string[] = ['EMI', 'Car', 'Food&apos ...

The 'XX' Typescript type does not match the type import ("/Volumes/D/test").XX.ts(2322)

I wrote a piece of code to customize the default configuration for a Class, but I encountered an unusual error message: Type 'IConfig' is not assignable to type 'import("/Volumes/D/www/js/tsc_1/test").IConfig'.ts(2322) It seems that I ...

Next.js is failing to infer types from getServerSideProps to NextPage

It seems like the data type specified in getServerSideProps is not being correctly passed to the page. Here is the defined model: export type TypeUser = { _id?: Types.ObjectId; name: string; email: string; image: string; emailVerified: null; p ...

Is there a way to prevent prettier from automatically adding a new line when formatting HTML tags with ">"?

While navigating through the Prettier extension in Vscode, I am struggling to find a way to disable a specific scenario. In particular, I am having trouble with the formatting of an html tag. Below is a snippet of code that requires some adjustments whene ...

Bring in exclusively typescript module declarations

In my various React projects, I find myself constantly declaring the same typescript modules, such as fonts.d.ts: declare module "*.woff"; declare module "*.woff2"; or images.d.ts: declare module "*.jpg" { const src: string ...

Changing the method signature in a TypeScript interface to replace/override the original one

For this specific scenario, the Array<T> interface is being extended in the following manner: interface BetterArray<T> extends Array<T> { push(this: BetterArray<T>, value: T): this; } Important note - the implementation of Arr ...

The attribute 'map' is not found on the data type 'Observable<[{}, {}]>'

Struggling to incorporate map, PublishReplay, and other rxjs functions into Angular6, I keep encountering a compilation error stating "Property 'map' does not exist on type 'Observable<[{}, {}]>'" every time. The same issue arises ...

Having trouble with Axios cross-origin POST request CORS error in React / Typescript, even after trying all the common solutions

I am encountering a CORS error in my React / Typescript project when trying to make a POST request using Axios. The project uses a Node.js / Express backend. Despite researching common CORS errors and reading highly-rated posts on the topic, I have been un ...

Injecting Services Error in Angular

I'm in the process of developing a web App and recently put together a new service: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ModuleService { constructor(private startTime: ...

Utilizing the "key" prop in React by spreading it into JSX with the getInputProps method from @conform-to/react

I am facing an issue in React where a key prop is complained about being spread into a JSX element, even when it’s not explicitly passed as part of the props. Take a look at this code snippet: <Input className="mb-[20px]" label="Fi ...

Can you explain the meaning of the type { [x: string]: any } to me?

After reading through this article, I'm having trouble understanding the signature: type FuncWithOneObjectArgument<P extends { [x: string]: any }, R> = (props: P) => R; I'm puzzled by what { [x: string]: any} represents. It seems like ...

An error arises in Typescript when the reducer state does not update upon clicking. The error message indicates that the properties 'state' and 'dispatch' are not recognized on the type 'UserContextType | null'

Having recently delved into typescript with react, I've encountered some issues. Despite trying various solutions, the state doesn't seem to work properly and I keep getting a typescript error stating: Property 'state and dispatch' does ...

Enhance your TypeScript code using decorators with inheritance

Exploring the realm of Typescript decorators has led me to discover their intriguing behavior when combined with class inheritance. Consider the following scenario: class A { @f() propA; } class B extends A { @f() propB; } class C exten ...

Angular 14: Enhance Your User Experience with Dynamic Angular Material Table Row Management

My inquiry: I have encountered an issue with the Angular material table. After installing and setting up my first table, I created a function to delete the last row. However, the table is not refreshing as expected. It only updates when I make a site chang ...