This course has been updated! We now recommend you take the TypeScript Fundamentals, v3 course.
Transcript from the "Type Conversion" Lesson
[00:00:00]
>> Mike North: So we've talked about the types of data, we've talked about the ways we can declare variables. And because Java Script's a dynamically typed language, it's not an untyped language, types exist. As in most dynamically typed languages things are converted as needed. So type conversion or type coercion, that is this phenomenon where the language tries to basically make sense of what you give it.
[00:00:27] So this one's pretty easy, 30 plus 7. There's no type conversion going on here. But if we were to do something like this, does anyone know what we might get?
>> Speaker 2: 44 of the string.
>> Mike North: Pardon?
>> Speaker 2: A string of 44. It would have been a number.
>> Mike North: You're, you are half right.
[00:00:46] Do you have a guess?
>> Speaker 3: It's not gonna be 377, is it?
>> Mike North: It's gonna be 377, awesome. Yeah, so you're, the half was basically whatever you use the addition operator. The plus operator, and there's a string involved. JavaScript will try to treat everything else as a string.
[00:01:06] Makes sense right? Not really. Do you have a question?
>> Speaker 3: Well, I was just gonna say, that plus always wants to concatenate right? But if you did a minus there it would do the math.
>> Mike North: That's true, have you seen this before?
>> Speaker 3: No, no, sorry, I wasn't cheating.
[00:01:22]
>> Mike North: [LAUGH] All right, how about this one? What's gonna happen here?
>> Speaker 2: Number 37.
>> Mike North: Number 37, so what we see here, this is a different operator. It's the third use of the plus sign. So we've got arithmetic, addition, right. We've got string concatenation. This is called the unary + operator.
[00:01:52] And it just tries to convert things into numbers, right. So the + operator here, when used with strings it tries it converts all other operands, the things that the operator is operating on, into strings. The unary plus operator tries to convert things to a number.
>> Mike North: Who's happy with this?
[00:02:13] There are no hands up in the room. This seems pretty confusing. This is like, people can be JavaScript programmers for years and years and years. And this kind of thing still snags them, particularly when you're dealing with the DOM. Has anyone ever gotten snagged by an input with a number in an input, and you kind of forget that these are always text values that come out.
[00:02:36] And now you're flip flopping between things. Not having types holds us back, so TypeScript aims to address some of this pain, right? To allow us to create JavaScript that doesn't fall into any of those unintuitive traps.