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

Connect Angular ngx-datatable accountid to a specific details page

My datatable is displaying static data with account numbers and other details, including a column for actions such as viewing a row. When I click on the button, an alert shows me the specific details. userdetails.component.ts rows: any = [ { id: 0 ...

What is the proper way to set up @Input?

I attempted to accomplish this in the following manner: @Input() data: any[] = []; Upon entering the ngOnInit lifecycle method, I notice that this.data is undefined: ngOnInit() { console.log(this.data); } Consequently, when trying to access th ...

The page is not responding after closing the modal dialog

My web application is built using Spring Boot for the backend and Thymeleaf for the front end. The app displays all available groups for users to review. When a user clicks on a group, the documents within that group are listed in a tabular form. Clicking ...

Is it necessary to incorporate express in a Next.js project?

I'm currently working on a website using Next.js. With Next.js, I have access to features like SSR and dynamic routing. Is it necessary for me to incorporate express into my project? If yes, what are the reasons behind needing to use it? What unique ...

What is the best way to specify the return type in TypeScript when there is a possibility of multiple types?

I'm currently working on implementing type definitions for an Axios API client but Iā€™m struggling with indicating to the compiler the specific return type that I am expecting. Here is a simplified example: import axios, { AxiosResponse } from "axi ...

Achieving the perfect alignment: Centering a paragraph containing an image using JQuery

I need help centering the background image of my <p> tag on the webpage. Script $(function() { $('ul.nav a').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ ...

Ways to retrieve the neighboring element's value and modify it with the help of JavaScript or jQuery

I am encountering a problem with selecting an adjacent element and updating its value. My goal is to update the input value by clicking the minus or plus buttons. I have successfully retrieved all the buttons and iterated through them, adding onclick eve ...

Deselect a checkbox that is already selected and choose the current option in the multiselect dropdown

I've created a code that allows for single select in a multiselect dropdown, disabling other options once one is chosen. However, I don't want to disable the checkboxes and would like to uncheck the selected option if a new one is chosen, all whi ...

Text transitions in a gentle fade effect, appearing and disappearing with each change

I want to create a smooth fade in and out effect for the text within a div when it changes or hides. After researching on Google and Stack Overflow, I found that most solutions involve adding a 'hide' CSS class and toggling it with a custom func ...

Populating form inputs with FCKeditor content prior to form submission

Currently, I am working on resolving an issue with a form on a website that relies on javascript for field validation. It has come to my attention that certain fields utilize fckeditor, causing the form field values to remain unset until the submit button ...

Exploring Elasticsearch with Ajax Query Syntax

Attempting to send a post request via AJAX to my Elasticsearch index but encountering some issues. Here's the cURL result: [~]$ curl -XGET 'http://localhost:9200/firebase/_search?q=song:i%20am%20in' {"took":172,"timed_out":false,"_shards": ...

What is the reason behind the ability to reassign an incompatible function to another in TypeScript?

I discovered this question while using the following guide: https://basarat.gitbooks.io/typescript/content/docs/types/type-compatibility.html#types-of-arguments. Here is an example snippet of code: /** Type Heirarchy */ interface Point2D { x: number; y: ...

What are the best practices for utilizing intro.js effectively on mobile devices?

Description When using introjs on mobile devices with a screen width of less than 600px, the tooltip ends up covering the element. When I hold the device horizontally, the tooltip adjusts its position accordingly. I attempted to apply custom CSS to the too ...

Learn how to display data from the console onto an HTML page using Angular 2

I am working on a page with 2 tabs. One tab is for displaying active messages and the other one is for closed messages. If the data active value is true, the active messages section in HTML should be populated accordingly. If the data active is false, th ...

Mocking multiple services and their constructors in an Angular 2 TypeScript Jasmine test component

I've got this login component code snippet that I need help testing in Angular. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@ ...

Creating a custom `onSubmit` function with Formik, TypeScript, and hooks can be a powerful way

I'm currently creating form onSubmit functions utilizing the useCallback hooks specifically designed for use with the formik library. A sample structure of my component using formik would be as follows: import { useContactForm } from './useCon ...

Effortless AJAX Submission and MySQL Data Refresh

I've hit a roadblock and can't seem to figure things out. I'm getting rid of my current code because it's not working well across different browsers, particularly when it comes to ajax submission. Could someone please provide me with a ...

What sets cross-fetch apart from isomorphic-fetch?

According to the Redux documentation, cross-fetch is the preferred choice, whereas most other sources recommend using isomorphic-fetch. What sets these two apart? ...

Executing a function in JavaScript using square brackets

While I was reading through the jQuery source code, I came across this interesting line: jQuery(this)[ state ? "show" : "hide" ](); Is there any particular benefit to using this syntax over the more traditional approach shown below? state ? jQuery(this) ...

Include a "remember me" feature in the Stripe form

I am currently working on an exciting project using Angular 6. Within my website, I have decided to integrate the Stripe payment system. However, I would like to incorporate a unique and default "remember me" feature offered by Stripe. <div id="card-e ...