In TypeScript, is there a similar concept to "sealed" or "final" modifiers?

I'm currently working on incorporating a method in a superclass that should be accessible for use, but not modifiable, in subclasses. Take a look at the following:

export abstract class BaseClass {
    universalBehavior(): void {
        doStuff(); // Perform some standardized actions consistently across all subclasses
        specializedBehavior(); // Delegate specialized actions to subclasses
    }

    protected abstract specializedBehavior(): void;
}

My aim is for any subclass of BaseClass to have the option to exclude the implementation of universalBehavior(), and furthermore, not even permitted to provide an implementation. Is this capability not yet feasible in TypeScript? Intellisense gives me errors when I omit the implementation in my subclasses. The most effective approach I've found so far is as follows:

export class SubClass extends BaseClass {
    universalBehavior(): void {
        super.universalBehavior();
    }

    specializedBehavior(): void {
        // Implement specific behavior for the subclass here
    }
}

Evidently, this poses an issue because I must ensure no subclass ever implements universalBehavior() with anything other than a call to super.universalBehavior().

Answer №2

Here is an innovative way to utilize the 'sealed method' as a readonly property of type function, demonstrating how it can trigger a compiler error when attempting to override it in an extended class:

abstract class BaseClass {
    protected element: JQuery<HTMLElement>;
    constructor(element: JQuery<HTMLElement>) {
        this.element = element;
    }
    readonly public dispose = (): void => {
        this.element.remove();
    }
}

class MyClass extends BaseClass {
    constructor(element: JQuery<HTMLElement>) {
        super(element);
    }
    public dispose(): void { } // Compiler error: "Property 'dispose' in type 'MyClass' is not assignable to the same property in base type 'BaseClass'"
}

In TypeScript 2.0, there is support for creating "final" classes by using a private constructor:

class A {
    private constructor(){}
}

class B extends A{} //Cannot extend a class 'A'. Class constructor is marked as private.ts(2675)

Answer №3

// Here is a clever trick I like to use:

export default class CreateHandler extends BaseHandler {
    // Using a final prop as a method
    public readonly create = (blueprint: Blueprint): Response<Record> => {
        return blueprint.create();
    };

    // Regular method for storing data
    public store(blueprint: Blueprint): Response<Record> {
        return this.response(blueprint.create());
    }
}

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

Tips for utilizing window.scrollTo in order to scroll inside an element:

I'm experiencing an issue where I have a vertical scrollbar for the entire page, and within that, there's an element (let's call it 'content') with a max-height and overflow-y scroll. The 'content' element contains child ...

Vitest's behavior shows variance when compared to compiled JavaScript

Challenge Currently, I am developing a package that relies on decorators to initialize class object properties. The specific decorator is expected to set the name property of the class. // index.ts const Property = (_target: any, key: any) => { } cl ...

An instance of an object is being added instead of parameters

I'm having some trouble making a server call using promises. Whenever I try to add my parameters, they end up showing as 'object%20Object' Here's the code snippet for the call: import { Injectable } from '@angular/core'; imp ...

Cypress: Conducting Test with Custom Timezone Setting on Windows

My testing environment was set up to run in UTC time zone. I utilized cy.clock() to initialize a date-time in UTC format, which the Web App will then display as the current browser date-time in UTC. In order to achieve this, I ensured TZ=UTC in my environ ...

Retrieve class property in Angular by its name

How can I retrieve an array from a class like the one below without using a switch statement, dictionary, or other collection to look up the name passed into the method? export class ProcessOptions { Arm = [{ name: 'Expedited Review ("ER") ...

Transform a struggling Observable into a successful one

When working with an HTTP service that returns an observable, I encountered an error during the subscribe process for a specific use case that I would like to address within the successful path. My scenario looks like this: In my service class: class My ...

Refreshing an array of objects within a record

I have the following data record stored in Algolia: enterprise_name:"manaslu enterprise", objectID:"14417261",_quotation:[{shamagri_title:"paper ad",price:4000, unit:"per sq inc", description:"5*5", geo_latitude:40, geo_longitude:89, type:"service"} ] I w ...

Clicking a button in React requires two clicks to update a boolean state by triggering the onClick event

I have a React functional component with input fields, a button, and a tooltip. The tooltip is initially disabled and should only be enabled and visible when the button is clicked and the input fields contain invalid values. The issue I'm facing is t ...

The module imported by Webpack appears to be nothing more than a blank

I am attempting to integrate the "virtual-select-plugin" library into my Typescript project using webpack. Unfortunately, this library does not have any type definitions. Upon installation via npm, I encountered the following error in the browser: TypeErro ...

The struggle of implementing useReducer and Context in TypeScript: A type error saga

Currently attempting to implement Auth using useReducer and Context in a React application, but encountering a type error with the following code snippet: <UserDispatchContext.Provider value={dispatch}> The error message reads as follows: Type &apos ...

Is there a way to create a stub for the given function using sinon?

Here is my test function: const customTestLibrary = require("./test"); describe("Initial Test", function() { it("should run the test function successfully", function(done) { customTestLibrary.execute(); done(); }); }); The te ...

How to Retrieve a Symbol in TypeScript

In the code snippet below, there is a function named factory that returns a Symbol of type Bob. However, TypeScript appears to forget the type of the return value immediately, leading to an error when trying to assign the return value to variable test one ...

Is it possible to retrieve a constant value while developing a customized rule in typescript-eslint?

I am currently working on implementing a custom ESLint rule using @typescript-eslint/utils that will display a warning if the prop kind of Category does not match a specific Regex pattern: import { ESLintUtils, TSESTree } from '@typescript-eslint/util ...

Is it possible to display Angular Material Slider after the label?

Searching through the Angular Material docks, I came across the Sliders feature. By default, the slider is displayed first, followed by its label like this: https://i.sstatic.net/C5LDj.png However, my goal is to have the text 'Auto Approve?' sh ...

Is a package I overlooked? The 'findOne' property is not found within the 'Schema<Document<any, {}>, Model<any, any>, undefined>'

I have taken over the responsibility of maintaining the websites at my company, and I am encountering the error message (Property 'findOne' does not exist on type 'Schema<Document<any, {}>, Model<any, any>, undefined>' ...

Error: This issue arises from either a glitch in the Node.js system or improper utilization of Node.js internals

I encountered an issue with setting cookies while creating an authentication mechanism for my service. You can read more about it here. Fortunately, I managed to solve the problem. The root of the problem was attempting to send cookies through 2 separate ...

Implementing the inheritance of variables from a subclass to fill an array based on user input: a step-by-step guide

I am currently working on an assignment for my Java class that involves making Shapes comparable by adding "implements Comparable" and creating the method: public int compareTo(Object o) in the abstract class Shape. For the comparison, we are supposed to ...

Exploring the communication between two components in Angular 2

My Angular components include: Create-Articles: used for creating articles. List Articles: utilized for listing all articles. The parent component is the Home Component. import { Component, OnInit } from '@angular/core'; @Component({ ...

Using Angular and Typescript to implement mathematical formulas involving date object subtraction

I need help converting the following Excel formula to Typescript. I keep running into an error that says 'The left-hand and right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type'. Can anyon ...

What is the best way to apply DateRange filtering in a Kendo Ui Grid?

Currently I am working with the Kendo Ui Grid and attempting to implement filtering by DateRange. Here is a snippet of my current code: HTML: <kendo-grid-column field="createdate" title="Creation Date" width="150"> <ng-template kendoGridFilterC ...