0

I have a function like this:

  private myFunc = (myNumber: number) => {
    if (myNumber === 1) {
        console.log('here');
    }
  }

Where myNumber is 1, I don't get the console output. From having a look at the console, I can see that myNumber is being treated as a different type (string). Changing the code like this works:

  private myFunc = (myNumber: number) => {
    if (myNumber == 1) {
        console.log('here');
    }
  }

I was under the impression that Typescript would issue a 'compile' error in this case, but it doesn't seem to. Can anyone tell me why?

2
  • Please show how the function is getting called. Commented Mar 4, 2019 at 16:22
  • The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal at runtime. Commented Mar 4, 2019 at 16:22

2 Answers 2

1

Yes, Typescript would show a compile time error if you'd do:

 myFunc("1");

However, as you seem to call it at runtime, Typescript can't check for it.

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

Comments

1

Typescript use a static type checking ( typescript is not present at the runtime ) so if you pass a string to the function 'myNumber' will be a string. You need to add your own check inside the function

  private myFunc = (myNumber: number) => {
    if (parseInt(myNumber) === 1) {
        console.log('here');
    }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.