Getters and Setters in TypeScript: How to Properly Use get and set?
Hi everyone! I just started learning TypeScript and switched from JavaScript. I think I understand classes, but I can't figure out getters and setters (get and set). \n\nI have a simple User class where I want to store first name and last name, and when accessing the fullName field, get them combined. I wrote this code:\n\n```typescript\nclass User {\n firstName: string;\n lastName: string;\n\n get fullName(): string {\n return `${this.firstName} ${this.lastName}`;\n }\n}\n\nconst user = new User();\nuser.firstName = "Ivan";\nuser.lastName = "Petrov";\nconsole.log(user.fullName); // "Ivan Petrov" - it works!\n```\n\nBut then I tried to make a setter for fullName so I could set the first and last name with a single string:\n\n```typescript\nclass User {\n firstName: string = '';\n lastName: string =
No answers yet.
Log in to leave an answer