0

I have a TypeScript class I want to use to manage a Checkbox. It looks like this:

export class TriStateCheckboxManager {

    constructor(public checkBox: HTMLInputElement) {
        if (checkBox.type != "checkbox") {
            // What now?
        }
    }
}

How can I raise an error if the checkbox's type is unequal to checkbox.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
ProfK
  • 49,207
  • 121
  • 399
  • 775
  • 1
    What do you want to do with that checkbox? – Fabian Lauer Mar 03 '13 at 12:34
  • Clarify your question please – thomaux Mar 03 '13 at 14:13
  • @Anzeo, much clearer can I make it? I want the `HTMLInputElement` object passed into the constructor have a `type` property of `checkbox` and I want to do something if it doesn't, like raise an exception, except I don't know if I can raise an exception, so I'm asking this question? – ProfK Mar 03 '13 at 17:19
  • @FabianLauer I want to manage it as a tri-state checkbox, hence the name of the class. – ProfK Mar 03 '13 at 17:20
  • "I don't know if I can raise an exception" -- what have you tried? – Ryan Cavanaugh Mar 03 '13 at 17:53
  • 1
    @RyanCavanaugh, when I embark on learning something, I take the evolved approach and read and ask questions, instead of randomly trying things. Try it, find out how to start a fire. – ProfK Mar 04 '13 at 21:24

1 Answers1

5

Because TypeScript is a supertset of JavaScript, it supports all built-in JavaScript functions, types, objects, keywords and so on. The one you are looking for is the throw keyword, that will raise the desired exception.

Your code so far was good, so the following will do the job.

export class TriStateCheckboxManager {

    constructor(public checkBox: HTMLInputElement) {
        if (checkBox.type !== "checkbox") {
            // checkBox doesn't meet the reqruirements,
            // so raise an error. Optionally, you could
            // log a message, warning or whatever you want
            // to the console.
            console.warn("checkBox.type doesn't match.", checkBox, this);
            throw "checkBox.type doesn't match."    // Throw anything you want here
        }
    }
}

BTW: It's strongly recommended to use !== and === for comparisons in JavaScript (thus TypeScript) instead of != and ==. See here for more.

EDIT: As MiMo said below, you can throw whatever type you want, so an object would be a suitable canditate too.

I found that this article looks promising if you're into JavaScript / TypeScript error handling. Here's the MDN page for throwing errors in JavaScript.

Community
  • 1
  • 1
Fabian Lauer
  • 511
  • 2
  • 12