wheatfairies
wheatfairies

Reputation: 355

Typescript Runtime Errors

I am relatively new to javascript/typescript and I'm getting a runtime error that I don't quite understand. I'm trying to create an instance of a TrailingAvg class, but my code breaks when i decalre it and produces a javascript runtime error - TrailingAvg is undefined. I though I set up the classes correctly and the syntax is being accepted, but I can't create this instance. What do I need to do to create an instance of a class in Typescript?

function drawChart(n) {
        uri = getURLParameter("url");
        setupHeader();
        setupMenu();
        var totalcount = 5;
        var prevmonth = 0;
        var trail = new TrailingAvg(n); //run time error here

    }
class TrailingAvg {
    totals: number[] = [];
    average: number;
    size: number;
    constructor(n: number) {
        this.size = n;
    }
    push(month, prevmonth, value) {
        var zeroes = month - prevmonth;
        for (var i = 0; i < zeroes; i++) {
            this.totals.shift();
            this.totals.push(0);
        }

        this.totals.push(value);
    }
    getAvg() {
        for (var i = 0; i < this.totals.length; i++) {
            this.average = this.average + this.totals[i];

        }
        return this.average;
    }
}

Upvotes: 1

Views: 1324

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220964

The class definition must come before any code that attempts to use it. This usually goes wrong in one of two ways:

Oops, I have two files now

Problem: You have foo.ts and decide to split it into foo.ts and bar.ts. This compiles into foo.js and bar.js, but your HTML page only says

<script src="foo.js"></script>

Solution: Fix your HTML page to have the additional script tag:

<script src="foo.js"></script>
<script src="bar.js"></script>

What's script ordering?

Problem: You have animal.ts and cat.ts, where cat.ts has some dependency on animal.ts. You write your HTML as:

<script src="cat.js"></script>
<script src="animal.js"></script>

and get a runtime error about something from animal.ts being undefined. This is because scripts execute in the order given in the page.

Solution: Order your files in dependency order:

<script src="animal.js"></script>
<script src="cat.js"></script>

Upvotes: 1

Related Questions