Enumerate the names of the private properties within the class

I am working on a problem where I need to use some of the class properties as values in a map within the class. In the example below, I have used an array instead of a map because when a property is marked private, it is not included in the keyof list. How can I specify key types if I want to include private property names?

var keys: Array<keyof A> = ["x", "y"]; // Error

class A {
  private x = 7;
  public y = 8;

  private keys: Array<keyof A> = ["x", "y"]; // Error
}

The same error occurs for both variables outside of the class and private properties within it:

Type '"x"' is not assignable to type '"y"'.

Answer №1

It's worth noting that when it comes to the private and protected properties of a class called C, they are not included in the list of keys returned by keyof C. This is intentional, as trying to access a private or protected property in this way would result in a compilation error. There has been a proposal on microsoft/TypeScript#22677 to enable mapping a type where these private/protected properties are made public, but as of TypeScript 4.9, this feature has not yet been implemented.

As demonstrated below, attempting to index into a class with private properties will cause errors:

namespace Privates {
  export class A {
    private x: string = "a";
    public y: number = 1;
    private keys: Array<keyof A> = ["x", "y"]; // Error
  }
  var keys: Array<keyof A> = ["x", "y"]; // Error
}
const privateA = new Privates.A();
privateA.y; // number
privateA.x; // error: private property
privateA.keys; // error: private property

However, if the goal is simply to hide certain properties from external users rather than making them explicitly private, a module or namespace can be used to selectively export only desired facets of the class:

namespace NotExported {
  class _A {
    x: string = "a";
    y: number = 1;
    keys: Array<keyof _A> = ["x", "y"]; // okay
  }
  export interface A extends Omit<_A, "x" | "keys"> {}
  export const A: new () => A = _A;
  var keys: Array<keyof _A> = ["x", "y"]; // okay
}

const notExportedA = new NotExported.A();
notExportedA.y; // number
notExportedA.x; // error: property not accessible
notExportedA.keys; // error: property not accessible

In the NotExported section, the internal details of the constructor and type _A are kept private. Only the necessary parts are exported through A. This approach maintains the desired behavior internally while limiting external visibility, similar to how Privates.A works. It focuses on not exposing implementation details rather than marking properties as private, recognizing that privacy in classes is more about access control than encapsulation.

Link to code

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

A guide on determining the number of rows in an ag-grid with TypeScript and Protractor

I am currently working on extracting the number of rows in an ag-grid. The table is structured as follows: <div class="ag-body-container" role="presentation" style="height: 500px; top: 0px; width: 1091px;"> <div role="row" row-index="0" row-id="0 ...

Can you provide guidance on how to pass props to a component through a prop in React when using TypeScript?

Hey there, I'm facing an issue with TypeScript where the JavaScript version of my code is functioning properly, but I'm having trouble getting the types to compile correctly. In an attempt to simplify things for this question, I've removed ...

What is the process of substituting types in typescript?

Imagine I have the following: type Person = { name: string hobbies: Array<string> } and then this: const people: Array<Person> = [{name: "rich", age: 28}] How can I add an age AND replace hobbies with a different type (Array< ...

How do I adjust brightness and contrast filters on a base64 URL?

When presented with an image in base64 format like this: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDAAwfqNRk/rjcYX+PxrV/wtWqwJSTlboMgAAAABJRU5ErkJggg== What is the most efficient method to programmatically alter a filter (such as brightness or cont ...

Populating a data grid with several objects within a JSON object

I am currently developing a project utilizing React with typescript and materialUi. My task is to retrieve data from a JSON fetch request and display it in a DataGrid. The structure of the JSON data is as follows: { id: "1234567890", number: ...

Automatically activate the Focus Filterfield in the ng-multiselect-dropdown upon clicking

I've integrated the ng-multiselect-dropdown package into my Angular project using this link: https://www.npmjs.com/package/ng-multiselect-dropdown. Everything is functioning as expected, but I'm looking to automatically focus on the filter input ...

The RxJs Observer connected to a websocket only triggers for a single subscriber

Currently, I am encapsulating a websocket within an RxJS observable in the following manner: this.wsObserver = Observable.create(observer=>{ this.websocket.onmessage = (evt) => { console.info("ws.onmessage: " + evt); ...

Bringing in Chai with Typescript

Currently attempting to incorporate chai into my typescript project. The javascript example for Chai is as follows: var should = require('chai').should(); I have downloaded the type definition using the command: tsd install chai After refere ...

Tips for turning off automatic retries in Nuxt 3 when utilizing useFetch

Struggling with the useFetch composable in Nuxt 3, I am facing an issue. I need the request to be triggered only once regardless of the result. Unfortunately, I haven't been able to figure out a way to achieve this. It keeps retrying when the request ...

Encountering a problem when utilizing window.ethereum in Next Js paired with ether JS

Experiencing some difficulties while utilizing the window.ethereum in the latest version of NextJs. Everything was functioning smoothly with NextJs 12, but after upgrading to NextJs 13, this error started popping up. Are there any alternative solutions ava ...

Error in Typescript: The property 'children' is not included in the type but is necessary in the 'CommonProps' type definition

Encountering this error for the first time, so please bear with me. While working on a project, I opened a file to make a change. However, instead of actually making any changes, I simply formatted the file using Prettier. Immediately after formatting, t ...

Creating dynamic queries in Nodejs using MongoDB aggregation with both AND and OR conditions

I am facing an issue with MongoDB aggregation in my nodejs code. const query = { '$expr':{ '$and':[ {'$eq': ['$appId', req.user.appId]}, ] } } A filter object is coming from the frontend: { shops ...

Disable all typings within a specified namespace for a specific file

I need to disable typechecking for a specific namespace called MyNamespace in a Typescript file. Is there a way to achieve this without affecting other files? ...

Can someone explain the meaning of this syntax in a TypeScript interface?

Just the other day, I was trying to incorporate the observer pattern into my Angular 4 application and came across this TypeScript code snippet. Unfortunately, I'm not quite sure what it means. Here's the code: module Patterns.Interfaces { ...

If the user clicks outside of the navigation menu, the menu is intended to close automatically, but unfortunately it

I have a nav file and a contextnav file. I've added code to the nav file to close the navigation when clicking outside of it, but it's not working. How can I ensure that the open navigation closes when clicking outside of it? Both files are in ts ...

Encountered a type error during project compilation: "Type '(e: ChangeEvent<{ value: string[] | unknown; }>) => void' error occurred."

I recently started working with react and I'm facing an issue with a CustomMultiSelect component in my project. When I try to call events in another component, I encounter the following error during the project build: ERROR: [BUILD] Failed to compile ...

TypeScript operates under the assumption that every key will be present on a Record object

Check out this code snippet: declare const foo: Record<string, number> const x = foo['some-key'] TypeScript indicates that x is of type number. It would be more accurate to say x is of type number | undefined, as there is no guarantee th ...

Ensuring the proper export of global.d.ts in an npm package

I'm looking to release a typescript npm package with embedded types, and my file structure is set up like so dist/ [...see below] src/ global.d.ts index.ts otherfile.ts test/ examples/ To illustrate, the global.d.ts file contains typings ...

Is there a possibility in TypeScript to indicate "as well as any additional ones"?

When working with typescript, it's important to define the variable type. Consider this example: userData: {id: number, name: string}; But what if you want to allow other keys with any types that won't be validated? Is there a way to achieve thi ...

Is there a way to customize the styles for the material UI alert component?

My journey with Typescript is relatively new, and I've recently built a snackbar component using React Context. However, when attempting to set the Alert severity, I encountered this error: "Type 'string' is not assignable to type 'Colo ...