Parameters and Return Types

Annotate the parameters; let the return type be inferred unless stating it adds something.

Stating it does add something in one important case: it makes the compiler check the function against your intention, rather than infer whatever your mistake produced. A function meant to return a number that accidentally returns a string is only caught if you said what it should return.

Try it

Which error message would you rather receive at 5pm?

loading editor…

checking…

Two versions of the same mistake. The first reports it where the mistake is; the second reports it wherever somebody uses the result.

Optional and default parameters.

function f(a: string, b?: number) makes b optional, so its type is number | undefined and you must handle that.

function f(a: string, b = 0) gives b a default, which also gives it its type, and it is never undefined inside.

Optional parameters must come after required ones, for the obvious reason.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Functions as Values →
← Back