Essential Types And Notations 20 exercises

Annotating Function Parameters

The error message about the implicit 'any' type is similar to what we saw with the add function.

This time, we will update the function declaration parameters so that a and b are both specified as string:

const concatTwoStrings = (a: string, b: string) => {
return [a, b].

Loading solution


00:00 Predictably, this error is very similar to solve as the first one, except here we're just annotating some empty parameters instead of annotating parameters that have types already. So what we do is we use this colon syntax and we say A is a string and B is also a string.

00:15 Now this colon syntax basically describes to TypeScript what A is going to be and what B is going to be. If we remove this, let's say we remove the one from A, then we get on this A, parameter A implicitly has an AnyType. Now what does that mean? Well, we can see from the translation here, I don't know what A is supposed to be, so I've defaulted it to Any.

00:36 Your TSConfig file says I should throw an error here. Now why should it throw an error in this position? Well, because TypeScript doesn't understand what type this A is supposed to be. And so by sort of a default level of strictness that people have agreed to, TypeScript thinks it should throw an error here.

00:54 And it's absolutely right because it can't really work out based on this whole setup what the exact type A and B should be. So whenever you're annotating a function parameter, you always have to give it a type. And in this case, the perfect type is string here and string or string for A and string for B.