Beginner's TypeScript Section 18 exercises
solution

Fix the Implicit 'Any' Error

'a' implicitly has an 'any' type.

This error occurs because TypeScript doesn't have enough information to infer a type, so defaults it to 'any'.

The solution is to add type annotations to the function's arguments.

In this case, both a and b should be typed as number:

export
Loading solution

Transcript

0:00 The solution, then, is to add some type annotations to the function's arguments. A, now, is typed as a number and B is typed a number. We can change this, if we want to. We can change this to string and string here, but then we start getting errors further down, addTwoNumbers.
0:19 It says, "Argument of type 'number' is not assignable to parameter of type 'string'". We'd have to parse in a couple of strings here. Then, of course, things are going to fail at runtime.

0:31 This idea that you need to annotate and make TypeScript understand the contracts that your functions must meet, the things you must parse into your functions, is critical to understanding TypeScript.

0:46 We could change this to a boolean, as well, if we want to. Actually, booleans can't be added together here. "Operator '+' cannot be applied to types 'boolean' and 'number'". You can't add a boolean to a number.

0:56 Weirdly, you can add a string to a number here, but what would happen is it would get appended together. We would have a two here. It's expecting it to be a number six, but it actually ends up being 24 there because it's adding the four, concatenating it to the two.

1:15 You may be asking yourself why doesn't TypeScript understand this? It sees that there's a plus between the two things here. Why can't it understand that A is a number and B is a number without us needing to add this?

1:29 Well, it's because TypeScript, at the source of its functions, like whenever you create a function you need to make that contract so TypeScript understands what you can parse to the function exactly. That's one of TypeScript's fundamental rules, is that every function you create you must always specify the types of each argument.

1:53 If you don't, you're going to get this pretty confusing error, but that's exactly what this error means. In tsconfig, we have enabled strict mode. Strict mode means that if you don't specify these, then you're going to get an error.

2:08 I recommend turning on strict mode for all TypeScript projects. That is your first solution. Well done.