none
TypeScript: using classes between files

    Question

  • I have added 2 TypeScript files:

    1. TypeScript1.ts

    export class Calculator {
        add(x: number, y: number): number {
            return x + y;
        };
        constructor() { }
    }

    2. UnitTest1.ts

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

    describe("all tests", () => {
        var subject: Calculator;
        beforeEach(function () {
            subject = new Calculator();
        });

        describe('#add', () => {
            it('Should add two numbers together', () => {
                var result: number = subject.add(2, 3);
                if (result !== 5) {
                    throw new Error('Expected 2 + 3 = 5 but was ' + result);
                }
            });
        });
    });

    In second file an error is highlighted: Cannot find name 'Calculator':

    if I copy text into one file, error disappears. What do I do wrong?

    I need to split this code between different files.

    Visual Studio Community 2015 + Node.js Tools

    "Blank Node.js Console Application" project template

    Wednesday, November 25, 2015 7:39 PM

Answers

All replies

  • Some of the examples use modules. Try this:

    module MyModule
    {
        export class Calculator
        {
            . . .
        }
    }

    Then use MyModule.Calculator in your tests.

    Wednesday, November 25, 2015 8:23 PM
  • Thank you for reply Viorel_,

    Now file look like this:

    module MyModule {

    export class Calculator {

    add(x: number, y: number): number {

    return x + y;

    };

    constructor() { }

    }

    }

    And I do not get errors on building stage.

    Now it is an error when test are being performed:

    ReferenceError: MyModule is not defined.

    I also tried to call the same from Node.js application, app.ts:

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

    console.log('Hello world');

    var subject: MyModule.Calculator;

    subject = new MyModule.Calculator();

    var result: number = subject.add(2, 3);

    console.log(result);

    In this case I get the same error:

    Wednesday, November 25, 2015 8:57 PM
  • You might try them over here.

    http://stackoverflow.com/questions/tagged/typescript

     

     

     


    Regards, Dave Patrick ....
    Microsoft Certified Professional
    Microsoft MVP [Windows]

    Disclaimer: This posting is provided "AS IS" with no warranties or guarantees , and confers no rights.

    Thursday, November 26, 2015 11:14 AM
    Moderator