Function Relationship with "this"
In this lesson, you will learn about the relationship of functions with the "this" keyword.
We'll cover the following
Function and this
TypeScript has the capability of letting the author of a function specify the type of this
. Without it, even with the arrow function, this may be of type any
. The lack of a type on this often occurs if you are using an object literal with a function that returns a function that uses this
. The function in the object literal is called a function expression and returns any
type when the value is accessed with this
.
However, we know that the type means the object literal, hence we can specify to TypeScript the type of this one. The syntax is to use this
followed by a colon symbol, followed by the expected type as the first parameter of the function signature.
In the following example, line 12 returns any
when you may expect a string
since the type on line 2 is an array of string
.
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy