Search code examples
typescriptkonvajskonva

Typescript augmenting/monkey-patching a new attribute for Konva classes


I am new to typescript and having trouble to monkey-patch a new attribute '_model' referring to my data-model with one of the classes of the Konva library.

The idea is to have the model available during the mouse interaction events and be able to modify it based on the changes. Therefore I'm trying to augment the Konva primitives with a '_model' attribute e.g. file test.d.ts:

import { Konva } from 'konva';

interface JsonModel {
    x: number
    y: number
    radius: number
}

declare module "konva" {

    namespace Konva {
        interface Circle {
            _model: JsonModel
        }
    }
}

file test.ts:

import Konva from "konva";

let circle = new Konva.Circle()
circle._model = {x:100, y:100, radius: 20}    
//     ^^^^^^

I get a compile error "Property '_model' does not exist on type 'Circle'", maybe this has something to do with the namespace not being imported correctly so the attribute is augmented with the wrong class? Thanks in advance for any help on this


Solution

  • Not a direct answer to your question. But instead of doing typescript magic, just write your data as a custom attribute. Typescript will understand it:

    import Konva from "konva";
    
    let circle = new Konva.Circle()
    circle.setAttr('_model', {x:100, y:100, radius: 20});
    circle.getAttr('_model');