0

I'm developing a small app in Angular 2 with TypeScript, and I've run into an issue.

Suppose I have a variable num declared as a number and I'm using ngModel to bind it to an input box in a form. When I get the value back, and check the type, it is actually now a string, and not a number anymore, so when do a check for num >= 0, it actually comes back true if the input contains empty string because of normal JavaScript behavior.

Now is this a bug in TypeScript or is there some way to get the correct datatype back? I would expect them to be doing proper coercion behind the scenes so I don't have to.

EDIT: plunk here

4
  • 1
    Can you create a plunkr demonstrating the issue? Commented Mar 2, 2017 at 4:30
  • @pixelbits Done Commented Mar 2, 2017 at 4:52
  • I would also appreciate getting some explanations as to why I'm being inexplicably downvoted Commented Mar 2, 2017 at 4:53
  • 1
    I would also agree that the down voting is unwarranted. Just because someone has a misconception about something, doesn't mean they don't deserve an answer. (Don't sweat it :) ) Commented Mar 2, 2017 at 5:19

2 Answers 2

3

This is not a bug in TypeScript, this is a correct behavior.

If you declared your input like

<input type="number" placeholder="Payment" [(ngModel)]="payment" value="" />

See the type="number" Then it will be a number.

Btw, I didn't downvote you :p

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

Comments

2

Just to try to add a bit of an explanation:

Typescript doesn't exist in the browser - it does no type coercion, no type checking no nothing. The type of the payment variable is determined by the input type and Angular (as Hung Cao explained).

Typescript only helps you in the editor and during the javascript compilation phase by checking your types.

If you create a library using TS and declare:

const myVariable: SomeClassOfMine;

and then I use it in different project, I can do:

myVariable = 1;

and there will be no warning/error. In fact the browser has no knowledge of your SomeClassOfMine type.

Just remember that TS doesn't exist in the browser (or node), it's still JS.

1 Comment

Well maybe it's just too late for me to be programming and it just wasn't making sense to me at the time but thanks for the explanation

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.