Creating a TypeScript class without using the prototype method

Recently delving into TypeScript and encountering a perplexing issue for which I can't seem to locate a satisfactory explanation...

Let's suppose I have a function:

function test() {
    function localAccessMethod() {
        console.log('I am only accessible from inside the function :)');
    }

    this.exposedMethod = function () {
        console.log('I can access local method :P');

        localAccessMethod();
    }
}

Now, the task at hand is to transform this function into a TypeScript class. Up until now, my progress is as follows:

class test {

    constructor: {}

    exposedMethod() {
        console.log('I can access local method :P');

        localAccessMethod();
    }

}

The challenge lies in defining that local function within the TypeScript class without exposing it through the prototype or .this. Is there a way to achieve this?

Alternatively, how should I modify the source code to comply with TypeScript conventions? I aim to create a function that is accessible to all class methods only, without being exposed...

Answer №1

To restrict access, utilize the private static keywords:

class Example
{
  private static restrictedMethod()
  {
    console.log('You can only access me from within this function :)');
  }

  publicMethod()
  {
    console.log('I have access to the local method :P');
    Example.restrictedMethod();
  }
}

Answer №2

In JavaScript, even private/protected members/methods are exposed, as only the compiler enforces visibility.

You have several options to work around this:

(1) Keep the "inner" function inside the main function:

export class test {
    constructor() {}

    exposedMethod() {
        console.log('I can access local method :P');

        function localAccessMethod() {
            console.log('I am only accessible from inside the function :)');
        }

        localAccessMethod();
    }
}

(2) If this is a module, place the inner function at the top level of the module and do not export it:

function localAccessMethod() {
    console.log('I am only accessible from inside the function :)');
}

export class test {
    constructor() {}

    exposedMethod() {
        console.log('I can access local method :P');

        localAccessMethod();
    }
}

(3) If you are not using modules, enclose the code in a namespace and export only the class:

namespace wrapping {
    function localAccessMethod() {
        console.log('I am only accessible from inside the function :)');
    }

    export class test {
        constructor() {}

        exposedMethod() {
            console.log('I can access local method :P');

            localAccessMethod();
        }
    }
}

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 are some methods for retrieving RTK Query data beyond the confines of a component?

In my React Typescript app using RTK Query, I am working on implementing custom selectors. However, I need to fetch data from another endpoint to achieve this: store.dispatch(userApiSlice.endpoints.check.initiate(undefined)) const data = userApiSlice.endpo ...

Guide on creating a server-side middleware in Next.js

In my upcoming nextjs project, which is a monorepo with both frontend and backend components, I am in need of a middleware to intercept requests. This middleware will handle tasks such as authentication and other necessary controls for every API call. Alth ...

Arranging Data in AngularJS based on Selected Filter Criteria

I have a filter function that currently only returns the name values in my table. I would like to add options for both ascending and descending sorting to this filter. Progress So Far: I am able to retrieve values from all inputs, including the name and ...

In TypeScript, how does "number" differ from "Number"?

Within the realm of TypeScript, there exist two distinct variations of the "number" type. The first is denoted as lowercase number, whereas the second is represented in uppercase as Number. Attempting to display number results in a compiler error: console. ...

Ways to develop a dynamic Promise-returning Function

I find myself in a situation where I am aware of the type of data that will be returned when making a request to an API. Here is the function I have: const fetchData = async (url: string, options?: Object): Promise<any> => { const res = await f ...

Using useState to initialize a long value

Obtaining a very large state from JSON can be challenging, especially when it consists of at least 50 lines. During page generation, an error like "there is no such value" may occur if the initial value is not set and the interface is not assigned properl ...

Using Material UI with React and TypeScript

I need some assistance with organizing my menus correctly in React using TypeScript. Currently, they are displaying on top of each other instead of within their respective category menus. I have been struggling to find a solution and would appreciate any h ...

The JavaScript code is executing before the SPFX Web Part has finished loading on the SharePoint page

I recently set up a Sharepoint Page with a custom masterpage, where I deployed my SPFx Webpart that requires certain javascript files. While the Webpart functions correctly at times, there are instances when it doesn't work due to the javascript bein ...

Best practices for organizing API Services using TypeScript and Next.js Server Actions

My product-actions/index file contains various server actions such as createProduct and getProductAssets, each of which verifies the user session before processing the request. I am looking for a way to check the session validity only once and then procee ...

Update the TypeScript definitions in the index.d.ts file using the npm command, by overriding it with the reference types

After running npm install, I noticed that the index.d.ts file contains a reference to the wrong path: /// <reference types="[WrongPath]"/>. As someone new to npm, TypeScript, and web development in general, I'm wondering if it's possible t ...

Guide on incorporating external .d.ts files for a module

I'm currently delving into the process of utilizing an external .d.ts file that is not included in the module. My intention is to make use of xlsx, which lacks its own type definitions, and instead incorporate them from the package @types/xlsx. Afte ...

Ionic Vue is throwing an error indicating that a property is not found on the type '{ $route(currentRoute: any): void; }'

Currently, I am developing an Ionic WebApp using Vue and TypeScript. My current task involves retrieving the current id parsed by the route. To achieve this, I have been working on a watcher: export default { data() { return { ...

Upon deployment, Angular encounters issues with routing to lazy loaded modules

I recently completed development on a new Angular application that utilizes lazy loading for improved performance. During local testing using ng serve (or ng serve --prod to mimic production mode), the app compiled without errors and functioned properly. ...

Utilizing Angular Components Across Various Layers: A Guide

Consider the following component structure: app1 -- app1.component.html -- app1.component.ts parent1 parent2 app2 -- app2.component.html -- app2.component.ts Is it possible to efficiently reuse the app2 component within the ap ...

What is the reason `addEventListener` does not work with a class method?

Recently, I discovered that the listener passed to addEventListener can actually be an object with a handleEvent function instead of just a callback function (here). However, I encountered an issue when trying to use handleEvent as a class method: class F ...

Preserving ES6 syntax while transpiling using Typescript

I have a question regarding keeping ES6 syntax when transpiling to JavaScript. For example, if I write the following code: class Person { public name: string; constructor(name: string) { this.name = name; } } let person = new Person('John D ...

Exploring the power of Prosemirror with NextJS through Tiptap v2

Greetings everyone, I am a newcomer to Stack Overflow and I am reaching out for assistance regarding an issue that has arisen. The problem at hand pertains to the development of the Minimum Viable Product (MVP) for my startup which specializes in creating ...

HTML not updating after a change in properties

My template is structured as a table where I update a column based on a button click that changes the props. Even though the props are updated, I do not see the template re-rendered. However, since I am also caching values for other rows in translatedMessa ...

Using Typescript: Defining a function parameter that can be either of two interfaces

While browsing through this specific question, I noticed that it was somewhat related to my current issue, although there were notable differences. In my scenario, I have a function named parseScanResults which accepts an object as its argument. This obje ...

Creating an instance of a class using a class decorator, with or without the 'new'

Seeking alternatives to creating class instances without using the new keyword in TypeScript, I came across this excellent solution that works seamlessly in JavaScript. The code found in the repository mentioned https://github.com/digital-flowers/classy- ...