Reputation: 377
I have little issue accessing object property in typscript. this works fine in js but doesn't in ts
let getUserName = {
firstname : "timi",
lastname: "oluwayomi",
middlename: "ola",
full : () => { return this.firstname + this.lastname + this.middlename } ,
first: () => { return this.firstname }
}
console.log(getUserName.first())
in javascript output: timi but ts throws error. is there a different way to access it in ts ?
Upvotes: 0
Views: 95
Reputation: 2790
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;
},
};
Upvotes: 1
Reputation: 377
i was working on an component based project "Angular" so i had to initialize first
getUserName : any;
getUserName = {
firstname : "timi",
lastname: "oluwayomi",
middlename: "ola",
full : () => { return getUserName.firstname + getUserName.lastname + getUserName.middlename } ,
first: () => { return getUserName.firstname }
}
console.log(getUserName.first())
also thanks to Dean Van Greunen
Upvotes: 1
Reputation: 7294
this inside arrow function refers to the global object, so its giving error, you can try with traditional functions
let getUserName = {
firstname : "timi",
lastname: "oluwayomi",
middlename: "ola",
full : function() { return this.firstname + this.lastname + this.middlename } ,
first: function() { return this.firstname }
}
console.log(getUserName.first())
Upvotes: 1
Reputation: 6327
just refer to the same object in the object, this is a hack IMO
let getUserName = {
firstname : "timi",
lastname: "oluwayomi",
middlename: "ola",
full : () => { return getUserName.firstname + getUserName.lastname + getUserName.middlename } ,
first: () => { return getUserName.firstname }
}
console.log(getUserName.first())
Upvotes: 1