Utilizing getter and setter functions within a setter with a type guard

I need to implement a getter and setter in my class. The setter should accept a querySelector, while the getter is expected to return a new type called pageSections.

The challenge I'm facing is that both the getter and setter must have the same argument/return value, but I want to include a type guard in the setter. The pageSections type is well-defined in a separate type definition file.

// Example usage within the code ...
this.parent(this.closest('page-sections'))

// Class definition
PageSection {
  private _parent: pageSections = undefined

  /**
   * @method setter parent
   * @description Set the parent property
   */
  set parent (parent: pageSections) {
    if (this._parent === parent) return
    if (typeof parent.current === undefined) return // This check ensures it is of type pageSections
    this._parent = parent
  }

  /**
   * @method getter parent
   * @description Get the parent property
   */
  get parent (): pageSections {
    return this._parent
  }
}  

What could be missing here? How would you suggest approaching this issue?

Answer №1

It is not possible to perform that action, and why would it even be necessary?

Here are some alternatives you can consider:

  • Create a new method (setParent(q:querySelector))
  • Develop a converter that analyzes the querySelector and generates a pageSections to be set using "set parent"

You may also want to check out this issue related to the topic (which has been under discussion since 2015).

Answer №2

If you're looking to perform argument checks, consider using the following package:

@p4ck493/ts-is

An example of how this package can be utilized for checking arguments can be found here:

@p4ck493/ts-is#-additional

However, remember that in your scenario, you will need a declared class on which these checks will be executed.

UDP:

In the provided code snippet:

import {TypeGuard} from '@p4ck493/ts-type-guard';
import {is, RegisterInIs} from '@p4ck493/ts-is';

// in the code …
this.parent(this.closest('page-sections'))

// in the class
@RegisterInIs()
PageSection {
  private _parent: pageSections = undefined

  /**
   * @method setter parent
   * @description set the parent property
   */
   @TypeGuard([is.PageSection])
  set parent (parent: pageSections) {
    if (this._parent === parent) return
    // if (typeof parent.current === undefined) return // this validates it being a pageSections for now
    this._parent = parent
  }

  /**
   * @method getter parent
   * @description get the parent property
   */
   @TypeGuard({
    result: [is.PageSection]
  })
  get parent (): pageSections {
    return this._parent
  }
}

If you require similar functionality in JavaScript, refer to this answer:

And just to clarify, I am the creator of the mentioned package, Harrison. Thank you for your interest and feedback.

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

What is the procedure for modifying the height of a button in HTML?

I wanted to add a flashing "Contact Us" button to the menu bar of my website to immediately attract people's attention when they visit. Here is the javascript code I used: <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&g ...

The statement ... is not a valid function, it has returned undefined

Currently experimenting with AngularJS, encountered an error message: Argument 'Controller' is not a function, got undefined View the JSFiddle link, along with HTML code: <h2>Hata's Tree-Like Set</h2> <div ng-app ng-init="N=3 ...

Having an issue with my code in angular 12 where I am unable to successfully call an API to retrieve a token, and then pass that token to another API for further processing

Here is the code snippet containing two methods: getToken and validateuser. I am fetching the token from getToken and passing it as a parameter to validateuser. However, before retrieving the token, my second API call is being executed. ...

Executing external Javascript within an HTML document

Just diving into this realm, so please have patience with me. I've got an external js file linked in my HTML. The JS code is solid and functions properly in Fiddle - https://jsfiddle.net/0hu4fs4y/ <script src="js/noti.js"></script> <sc ...

In Javascript, you can quickly update other variables with just a one-line conditional statement

Is there a way to simplify this code into one line without using an if-else statement? For example, updating all variables when a specific condition is met? const dogStatus = present ? "bark" : "beep"; const catStatus = present ? "meow" : "meep"; const f ...

The Express application encounters a 500 Internal Server Error due to a TypeError where the Object #<EventEmitter> does not contain the method 'hr

The staging instance of my webapp is encountering an issue: Express 500 TypeError: Object #<EventEmitter> has no method 'hrtime' at Object.logger [as handle] (F:\approot\node_modules\express\node_modules\connect ...

Steps for inserting a video into a new div upon selecting a hyperlink

Looking for a way to link menu elements to corresponding videos in adjacent divs? I have two divs set up - one with the menu list and another right next to it where the videos should be loaded. Forms seem like a potential solution, but I lack expertise i ...

Preventing CSRF attacks using AJAX in a Django application

After some troubleshooting, I discovered the mistake in my HTML code. Simply adding {% csrf_token %} resolved the issue :) Big thanks to everyone who helped! (I followed the JavaScript snippet provided in the initial response but I'm still encounte ...

Error encountered while executing node server.js for Azure IoT Hub due to incorrect flags provided in the RegExp constructor

Currently, I am attempting to execute 'node server.js' in order to establish a connection between my Raspberry Pi device and Azure through the Azure IoT Hub. However, upon running the command 'node server.js', an error message is displa ...

Expand and collapse divs using jQuery when a JavaScript do_PostBack link is clicked

Currently, I am in the process of developing a website called TheDigitalScale. One particular feature on the site involves using jQuery to create an expanding div that opens when clicked and closes with another click. <script type="text/javascript"> ...

Angular 2 GET request returns a 404 error

I have been attempting to reproduce the ngPrime datatable demo from this Github repository. Currently, I am working with the most recent version of Angular (4) and using angular-cli in development mode. Placing a JSON file into my app folder where the serv ...

JavaScript array contains duplicate values

I have developed a custom Asp.Net user control. To keep things simple, I have omitted some of the HTML code. <asp:Panel ID="PanelInputControl" runat="server" CssClass="input-control input-period"> <div ID="InputWrapperMonth" runat="server" c ...

Enhancing highcharts gauge with dynamic data from JSON

I've been working hard to get my Gauge looking just right, and now I'm attempting to update it with JSON data from Thingspeak. However, when I check the page, I keep running into a ReferenceError - it says "data is not defined." If you want to t ...

Looking to create a GitHub example in Fiddle but running into issues with getting the result?

I've been working on an example on Fiddle, but it's not functioning as expected. I want to implement i18next so that the text changes when the user switches languages. After searching for a solution, I came across this GitHub repository: https:// ...

How to position footer at the bottom of Material UI cards - see example below

After getting inspiration from the material-ui example of cards, I wanted to create a grid layout with multiple cards. My goal was to make all the cards have equal height (which I achieved using height:100%) and position the footer at the bottom of each ca ...

Adding Logging Features in ASP.NET

I am currently working with an .ascx file that contains both JavaScript and div elements. I need to add a log statement inside a function for troubleshooting purposes. Can someone please guide me on how to achieve this? Below is a snippet of my code: fu ...

Commitment within a forEach iteration

While working with a foreach loop, I am facing some challenges. Here is the scenario: I have multiple elements stored in an object array. For each object, I need to execute two queries. After completing the queries for one object, I move on to the next and ...

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

Differences in accessing the previous state between React's useCallback and useState's setState(prevState)

It has come to my attention that useCallback functions recreate themselves when their dependencies change, acting as a sort of wrapper for memoizing functions. This can be particularly useful for ensuring access to the most up-to-date state in useEffect ca ...

Exploring AngularJS $compile and the concept of scoping within JavaScript windows

I've encountered a scoping issue with the use of this inside an angular-ui bootstrap modal. The code below functions perfectly outside of a modal, but encounters problems when run within one: var GlobalVariable = GlobalVariable || {}; (fun ...