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.

6
  • 1
    What do you want to do with that checkbox? Commented Mar 3, 2013 at 12:34
  • Clarify your question please Commented Mar 3, 2013 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? Commented Mar 3, 2013 at 17:19
  • @FabianLauer I want to manage it as a tri-state checkbox, hence the name of the class. Commented Mar 3, 2013 at 17:20
  • 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. Commented Mar 4, 2013 at 21:24

1 Answer 1

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.

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

2 Comments

I'd throw an object, not just a string
@MiMo: Good point. I'm gonna state that you can throw whatever you want. ( Even tomatoes? :) )

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.