3

How would I convert this function from Javascript to Typescript?

var ToggleSwitch = this.ToggleSwitch || (function () {
//Code
}

I know the var ToggleSwtich part can be written as export class ToggleSwitch {}, but I'm not sure about the rest of the line.

3 Answers 3

2

If you write a module, you'll end up with nearly identical code...

module ToggleSwitch {

}

Modules can be extended in TypeScript. The only difference is the compiler will know whether the module is already declared or not, which saves you the test.

To take this example further, here is an example with ToggleSwitch declared twice, with different contents. You'll notice that you can access all the contents. This can be split across multiple files:

module ToggleSwitch {
    export class a {
        go() {
            alert('a');
        }
    }
}

module ToggleSwitch {
    export class b {
        go() {
            alert('b');
        }
    }
}

var a = new ToggleSwitch.a();
var b = new ToggleSwitch.b();

a.go();
b.go();
Sign up to request clarification or add additional context in comments.

Comments

2

Typescript is supposedly a superset of Javascript, so inherently, any Javascript should be valid Typescript.

1 Comment

The TypeScript Wikipedia page says as much in the introduction.
1

Because TypeScript is a superset of JavaScript, most valid JavaScript is valid TypeScript too. In this case, your code (after adding a missing parenthesis at the end) is valid TypeScript and valid JavaScript.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.