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 ?
CodePudding user response:
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())
CodePudding user response:
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())
CodePudding user response:
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