TypeScript Fundamentals Type Conversion
This course has been updated! We now recommend you take the TypeScript Fundamentals, v3 course.
Transcript from the "Type Conversion" Lesson
>> 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?
[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.
>> 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?