2

I have an existing JavaScript object. I would like to use it in TypeScript as a type, but can't see any way to do it. For example, I have an JavaScript object constructor like this:

function Canvas2D(canvas)
{
    var context = canvas.getContext("2d");
    this.clear = function() { context.clearRect(canvas.width, canvas.height); }
    // lots more methods follow...
}

In my TypeScript I want to declare a variable that is an instance of Canvas2D. I could define it as type "any" but that doesn't give me auto-suggest and kind of negates the benefits of using TypeScript.

class MyApp
{
    private canvas2d: any;
    // I want this instead
    //private canvas2d: Canvas2D;

    constructor(aCanvas) { this.canvas2d = new Canvas2D(aCanvas); }
}

Is there a way to do this in TypeScript?

In JavaScript I could do this:

var canvas2D = new Canvas2D(aCanvas);

And it (Visual Studio) would know what type of object it was dealing with.

1 Answer 1

3

Yes it is possible. You can either port your Canvas2D object to a typescript class and reference the file

/// <reference path="Canvas2D.ts" />

inside of the MyApp file.

or

You can create a definition file (Canvas2D.d.ts) that defines the Canvas2D class shape and reference that instead.

/// <reference path="Canvas2D.d.ts" />

ex:

declare class Canvas2D {
    constructor(elem: HTMLCanvasElement);
    clear();
    // Lots more methods here...
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you Ryan, learned something new about declare class vs interface :)
Thanks for the help. I was hoping it would be easier than that, so I wouldn't have to do a lot of typing ;). I don't want to rewrite Canvas2D because I use it in JavaScript apps too (I just started playing with TypeScript). I was thinking I would have to create an interface but declare looks like it might be better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.