2

I have a method which launches a modalWindow which takes an element as input (using $event.target) or a number. I am trying to perform a check on the type of the input but the check always treats element as a number even if it's not. Whether or not element is a number the console.log is outputted and the else never runs.

launchModal(element: number | any) {

    if (<number>element) {

      console.log('ele as num', element);
    } else {
      const elementId = (event.target as Element).id;
      const elementIdArray = String(elementId).split('-');
      this.currentRow = parseInt(elementIdArray[2], 10);

    }
    this.loadEquipmentFullRowDataRequest(this.currentRow);

  }

I following the documentation for advanced types at the official site

2 Answers 2

3

In typescript the type system is compile time only, in runtime the code is transpiled to JavaScript and all the type information is lost.

When you say if (<number>element) the cast doesn't actually do anything, it just allows you to write code that refers to element as a number (here you aren't doing anything to element so it's meaningless).

In order to check if the value you got is really a number you have to use JavaScript methods:

if(typeof(element) === 'number')
Sign up to request clarification or add additional context in comments.

Comments

1

if(<number>element) does not type check if the element is a number, once compiled it will just check if element is not null or undefined.

Try the following:

const launchModal = (elem: number | HTMLElement) => {
    if (!elem) {
        return;
    }

    let row = elem as number;
    if (elem instanceof HTMLElement) {
        row = parseInt(elem.id.split('-')[2], 10);
    }

    // load row data
}

e.g. :

launchModal(10);

launchModal(document.getElementById('...'));

Comments

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.