You are accessing this
within an arrow function. Inside an arrow function, this
refers to the global object, not the execution context. See You Don't Know JS Yet - Chapter 3 - this
Keyword for more info on this
.
So, to start with, use this:
let getUserName = {
firstname : "timi",
lastname: "oluwayomi",
middlename: "ola",
full() { return this.firstname + this.lastname + this.middlename },
first() { return this.firstname },
}
As this
is of type any
in this case, as the TypeScript compiler cannot infer the type of your object for you, you will need to type the object yourself (usually a good idea anyway):
type GetUserName = {
firstname: string;
lastname: string;
middlename: string;
full(): string;
first(): string;
}
let getUserName: GetUserName = {
firstname: "timi",
lastname: "oluwayomi",
middlename: "ola",
full(this: GetUserName) {
return this.firstname + this.lastname + this.middlename;
},
first(this: GetUserName) {
return this.firstname;
},
};