1

Currently I have a large codebase developed with CoffeeScript and want to extend it with some TypeScript.

Let's say I have the following code in the CoffeeClass.coffee file:

define 'CoffeeClass', ->
  class CoffeeClass
    foo: () -> 1

It is meant to be loaded through require in the following manner (let's call this file CoffeeUser.coffee):

require ['CoffeeClass'], (CoffeeClass) ->
  class MyClass extends CoffeeClass
    foo: () -> super() + 1
  console.log (new MyClass().foo()) # => 2

Now it can be loaded in browser with the standard RequireJS markup:

<script data-main="CoffeeUser.js" src="require.js"></script>

I want to extend the CoffeeClass from the TypeScript code. That's what I've tried:

First write a CoffeeClass.d.ts definiton file (I know it is wrong but it's showing what I'm trying to achieve):

export class CoffeeClass {
  foo(): number;
}

And then try to use it from TypeScriptUser.ts:

import CoffeeClass = require('CoffeeClass');
class TypeScriptUser extends CoffeeClass {
  foo(): number {
    return super.foo() + 1;
  }
}

But it won't compile partly because I cannot find the right syntax for the d.ts file and partly because I cannot properly tell the compiler how to extend the CoffeeClass (as far as I can tell the compiler cannot understand that CoffeeClass is really a class and not just a module).

So can I tell the TypeScript compiler that the module is a class here? If no, how would you recommend me to change the CoffeeClass design to extend it from TypeScript code and don't lose all the type safety?

1 Answer 1

2

Finally I've found the solution. That's the special export = syntax. Here it is. CoffeeClass.d.ts:

declare class CoffeeClass {
    foo(): number;
}

export = CoffeeClass;

And TypeUser.ts:

/// <reference path="CoffeeClass.d.ts" />
import CoffeeClass = require('CoffeeClass')
class MyClass extends CoffeeClass {
    foo() {
        return super.foo() + 1;
    }
}

console.log(new MyClass().foo()); // => 2

Note that the compiler will infer the proper require call when compiling the code.

Sign up to request clarification or add additional context in comments.

Comments

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.