During application development, it may happen that you deal with a situation where you will know more about the value than TypeScript does. Most often in a situation, where you know that the type of a certain entity could be more specific than it is now.

Type assertion is a way to explicitly inform the compiler that you want to treat the entity as it would have a different type. This allows you to treat any as a number, or a number as a string. Let's have a look at the following example:

let someValue: any = "I am sure I am a string";

Although, we are sure that someValue contains a string, for the compiler it still has a type of any. As result, you won't be able to use methods like length() which is a default method for a string type variable. What you can do is to inform the compiler to treat it as a string. You can do this in two ways:

let strLength: number = (someValue).length;

Or using the as syntax:

let strLength: number = (someValue as string).length;

Probably you already know that in JavaScript you can define functions like the one below:

// Named function
function add(x, y) {
 return x + y;
}

// Call named function
console.log(add(5,10));

which are so-called Named functions. You can also use Anonymous functions:

// Anonymous function
let myAdd = function(x, y) { return x + y; };

// You can call it like this
console.log(myAdd(5,10));

// But definitely more common
console.log ((function(x , y) {
return x + y;
})(5,10));

An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation.

One common use for Anonymous functions is as arguments to other functions. Another common use is as a closure, for which see also the Closures chapter. Below shows its use as an argument to other functions:

setTimeout(function() {
alert('hello');
}, 1000);

Or call it with parameter:

(function(message) {
alert(message);
}('foo'));

So basically, you want to use Anonymous functions in all places where you have to use a function as an argument to other function or as a closure (we will learn about closures in later lessons).

In those cases you use the function only once, therefore you don't want to name it (like you would for a Named function) just to use it in a single line.

Anonymous functions might look confusing at the start, however, once you start using them you will find them very handy. But there is something else, another type of the function called an arrow function which we will learn about in the next lesson.