TypeScript Basics: Operators
Welcome to the Operators lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Operators like
+and*can only be used on types that make sense. For example, we can add numbers with+and multiply with*. We can also use+to concatenate strings. However, we can't use*on strings. That's a type error.(Some examples in this lesson will cause a type error. For those, you should answer with
type error.)>
1 + 1;Result:
2
>
2 * 2;Result:
4
>
'1' + '1';Result:
'11'
>
'2' * '2';Result:
type error: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
>
'4' / '2';Result:
type error: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
In JavaScript,
'a' * 'b'isNaN. If that happens in a real system, it's almost certainly a bug. TypeScript makes this type of bug nearly impossible!We also can't pass mixed types to operators if they don't make sense.
>
1 / '1';Result:
type error: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
However, TypeScript will still allow some questionable combinations. For example,
1 + '1'gives'11', as in JavaScript.>
1 + '1';Result:
'11'
>
'1' + 1;Result:
'11'