Getter and Setter Implementation in Typescript without Using Classes

Check out these various SO questions discussing Typescript getters/setters: from 2015, Jan 2018, Sept 2018, and more.

Now, the question arises - what is the best approach to define Typescript types for getters/setters in a plain JavaScript object without using the class syntax? Particularly focusing on understanding typing best practices. Let's take a look at the interface below -

interface Store {
   activeEvent: Date
}

Here are a few criteria for this object -

Avoid using new for instantiation

Avoid duplicate keys - as seen in the example that doesn't work

const Store: Store = {
  activeEvent: new Date(),
  get activeEvent() {
    return this.activeEvent;
  },
}

Avoid leading underscores, which can cause linting issues as per Airbnb's eslint config -

const Store: Store = {
  _activeEvent: {},
  get activeEvent() {
    return this._activeEvent;
  },

If possible, include default values but ensure they do not generate errors if the key is dropped, yet still have appropriate behavior when accessed for the first time. This could involve initializing and returning this.activeDate if it isn't defined initially. However, this blurs the line between a simple getter and a getter/setter method -

 get activeDate() {
    if(this.activeDate){ return this.activeDate }
    const date = new Date()
    this.activeDate = date;
    return date;
  },

Avoid creating redundant keys just to implement getters and setters. It's interesting to note that having the same key for both getter and setter might not produce errors, hinting at potential mistakes in implementation. Any insights on this matter would be greatly appreciated.

https://i.sstatic.net/mmGU0.png

Answer №1

To prevent name collision and infinite loop problems, it is recommended to encapsulate your object creation within a closure. Keep variables that are not part of the interface outside the object like this:

function createStorage() {
  let currentLocation = window.location.href;
  return {
    get currentLocation() {
      return currentLocation;
    },
  };
}

This approach ensures that the variable used by the getter (in this case .currentLocation) exists outside of the object's scope, within the createStorage function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 6 is throwing an error message stating that it cannot access the 'image' property of an undefined object

Having trouble retrieving the details, as it is rendering to the dom with an undefined error. Check out this image for reference: Welcome to the Book Details Component export class BookDetailsComponent implements OnInit { book: Book; books: Book[]; ...

What is the best way to implement a dynamic sidebar component using React and Material UI?

I have been attempting to implement a responsive sidebar using React Material Design, but I am struggling to achieve the desired outcome. The main goal is for the page content to remain responsive when the sidebar is opened, without overlapping on the pag ...

When changing recipients in Firebase, the Javascript code fetches the same message multiple times even though there is only a single message stored in the database

In the process of developing a chat application using Firebase and JavaScript, I have come across an issue. Whenever I switch receivers multiple times, the message I send is fetched multiple times even though it is only sent once to the database. var selec ...

What is the best way to create a nested match using regex?

const foundMatches = regExPattern.match(/\((.+?)\)/g); When tested against: [example[1]] The result is "[example[1]", indicating a potential nesting issue. How can this be resolved? ...

Unable to modify the Jest mock function's behavior

The issue I am facing involves the following steps: Setting up mocks in the beforeEach function Attempting to modify certain mock behaviors in specific tests where uniqueness is required Encountering difficulty in changing the values from the in ...

What is preventing me from using the "@" symbol to substitute the lengthy relative path in my __tests__ directory?

When I initialized my Vue project using vue-cli, I encountered an issue where the use of @ in my src folder was functioning correctly, but not in my __tests__ folder. I have already added configurations to my tsconfig.json file, although I am unsure if i ...

Effortlessly sending multiple values from text fields using jQuery

i am using jQuery to fetch all values from text fields with the same field name. $('input[name^="StudentName"]').each(function() { StudentName += $(this).val(); alert(StudentName); }); when I alert, all the values are displayed as one s ...

Sliding multiple divs up and down with jQuery

Here is the code that I am working with: JavaScript: $(".Head").click(function () { if ($(".Body").is(":hidden")) { $(".Body").slideDown('fast'); } else { $(".Body").slideUp('fast'); } }); HTML: ...

"Encountering a problem with the Flicker API while trying to view personal

I've been attempting to retrieve my personal photos using the following function with a node package obtained from this source https://www.npmjs.com/package/flickrapi\ When trying to access pictures of another user like 136485307@N06 (Apollo Im ...

The desktop display is experiencing a technical issue where menus are failing to appear

When my website is opened on desktop, the state remains false which causes no menus to show. I only want this functionality to be active on mobile devices. const Navbar = () => { const [isMenuOpen, setIsMenuOpen] = useState(false); const toggle = () ...

Guide to implementing an ES6 template within an HTML anchor tag href

Hello there, this is my first time seeking assistance here. I have an ajax request returning a JSON response. Now, I am aiming to use the response data to dynamically generate recipe titles and also create clickable links with that data. $( window ).load( ...

The use of callbacks is ineffective in addressing the asynchronous nature of

Hello everyone, I'm currently working on a weather app and I'm facing an issue with the asynchronous behavior of useState. I've come across some suggestions on Stack Overflow that using a callback in the useState function might solve the pro ...

Issue with Textarea not updating when props change in a React component

I am facing an issue with updating the default value of a textarea based on props passed from a parent component. Strangely, the update works when using 'value' but not when using 'defaultValue'. However, I need the textarea to be edita ...

ESlint is unable to parse typescript in .vue files

After using vue ui to build my project, here is the content of my package.json: "@vue/cli-plugin-eslint": "^4.1.0", "@vue/cli-plugin-typescript": "^4.1.0", "@vue/eslint-config-standard": "^4.0.0", "@vue/eslint-config-typescript": "^4.0.0", "eslint": "^5.1 ...

The canvas loadFromJson function fails to implement the font-family property

I have implemented the following code to display Google font and update the canvas: /* on change of font, load the preview and update the canvas */ $('#font').on('change', function () { $('.font_preview').show ...

There seems to be an issue with ngOptions in Angular as it is

Calling all angularjs experts for assistance... Currently integrating cake with angular. Utilizing a rest controller to enable communication and retrieve options in a serialized json format as displayed below Attempting to populate dropdown options: &l ...

Implementing proper data return in MVC4 through an Ajax call

When using ajax to call an action in a controller, the code may result like this: $.ajax({ type: "POST", url: "getUserInfo.json", data: "", success: function (data) { if (data.resultInfo.resu ...

Is there a glitch in the Selenium Java CSS Selector functionality?

Everything seems to be working smoothly with that code! It successfully locates and clicks on my button within the span tag. driver.findElement(By.cssSelector("span[id$=somePagesCollection] a")).click(); However, after clicking the button, an input field ...

Retrieve a specific attribute from a collection of JSON objects and transfer it to a separate object

Having a JSON object array with various project information: [ {"Project":"Project 1","Domain":"Domain1","Manager":"Manager1"}, {"Project":"Project 2","Domain":&q ...

What is the best way to trigger a refresh callback on Angular datatable pagination after updating the data

I've successfully set up my angular datatable configuration. Here's what it looks like: vm.dtOptions = DTOptionsBuilder.newOptions(). withPaginationType('full_numbers'). //withOption('ajax', { ...