Typescript: Concealing private keys within public objects

Can you add a private key to a public object?

export class user {
    public details: {
        lastname: string,
        firstname: string,
        username: string
    }
}

I want the username property to be accessible only within a specific method of the class. Can I achieve something like this:

export class user {
    public details: {
        lastname: string,
        firstname: string,
        private _username: string
    }

    public setUsername() {
        this.details._username = `${lastname} ${firstname}`;
    }
}

Answer ā„–1

Uncertain of the reasoning behind your request for this (and whether you truly desire behavior akin to `private` rather than just `readonly`), I would recommend encapsulating your classes within a module where only the intended public-facing types are exported. Consider the example below:

namespace Library {
  export interface Details {
    lastName: string;
    firstName: string;
  }
  interface PrivateDetails extends Details {
    username: string;
  }
  class PrivateUser {
    details: PrivateDetails;
    constructor(lastName: string, firstName: string) {
      this.details = { lastName, firstName, username: "" };
      this.setUsername(); 
    }
    setUsername() {
      this.details.username = `${this.details.lastName} ${this.details.firstName}`;
    }
  }
  export type User = Omit<PrivateUser, "details"> & {
    details: Details;
  };
  export const User: new (
    ...args: ConstructorParameters<typeof PrivateUser>
  ) => User = PrivateUser;
}

Within the library, there exists a `PrivateUser` class and a `PrivateDetails` type, where the `details` property of `PrivateUser` is of type `PrivateDetails`. These internal entities are not exposed. Instead, we export a `User` class* and a `Details` type, where the `details` property of `User` corresponds to `Details`. (*Note that both a `type` and a `const`, both named `User`, are actually being exported here. The `type` represents the instance type of `User`, while the `const` serves as the constructor. While a `class` declaration handles this automatically, it must be defined in two separate lines in this case).

Let's put this into action:

import User = Library.User;
const u = new User("Turing", "Alan");
console.log(u.details.firstName); // Turing
console.log(u.details.lastName); // Alan
console.log(u.details.username); // error!
// Property 'username' does not exist on type 'Details'.
// At runtime, however, it still outputs "Turing Alan" similar to a private property
u.details.lastName = "Alda";
u.setUsername(); 
console.log(u.details.username); 
// Still a compiler error, but at runtime output will be "Alda Alan"

This setup aligns with what you may desire. Internally within `Library`, `PrivateUser` has full access to its `details.username` property, whereas externally through the exposed `User` class, such access is restricted. Compiler errors will alert if attempted use occurs. Despite this, at runtime access remains feasible - behaving similarly to private properties.

Hopefully, this explanation proves beneficial. Best of luck!

Link to code

Answer ā„–2

What about simply

export class person {

    public lastName: string,
    public firstName: string,
    private _username: string

    public setUserName() {
        this._username = `${this.lastName} ${this.firstName}`;
    }
}

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

Utilize Angular 5 to create a Data Service for extracting JSON data from MongoDB

Seeking to incorporate a data service for reading json data from mongoDB, I initially implemented the function directly within the ngOnInit() of my component successfully. However, when attempting to create a separate data service, I encountered difficulti ...

Setting a default value for NULL property in TypeScript

Trying to establish a default value for all NULL objects has been quite the challenge. The current code looks like this: private setDisplayAmount(summaries: summary[]): void { summaries.map(t => { // performing some operations, and then... ...

Jasmine-ts is encountering a problem related to a subpath within a package, causing

Embarking on a journey of jasmine unit testing, I am encountering challenges when trying to run jasmine and locate my TypeScript written specs. Using jasmine-ts, I typically execute the following command: jasmine-ts --config=spec/support/jasmine.json The ...

The NgIf-Else statement is functioning incorrectly

As a novice in Angular 8, I am facing some challenges with a section of my code. Specifically, I am attempting to utilize the ngIf Else condition within a div to display a button based on the retrieved value. <div class="form-group"> <div c ...

What is the process for implementing an abstract factory pattern in Typescript?

Iā€™m currently facing a challenge while attempting to incorporate a standard abstract factory pattern in Typescript, only to find that the compiler is not quite on board with my efforts. Below is a simplified version of the code I am working with: abstra ...

Struggling with grasping the concept of Filtering Array in Eloquent Javascript Chapter 5?

Currently diving into the world of JavaScript through the enlightening pages of Eloquent JavaScript. Chapter 5 has been a breeze so far, except for one line of code inside a console.log statement that has me stumped: function filter(array, test) { ...

What is the method for retrieving values from an object using keys that are subject to change?

Here is the code snippet I am working with: bodyLength.forEach((el, i) => { console.log(`${values.bodyTitleEn2 + i.toString()}`); body.push({ title: [ { key: 'en', value: values.bodyTi ...

typescript the value property is of the type defined

I am currently struggling with defining the extension of type I have. This is what I currently have: type FooMap = {[key: string]: Foo<any>}; However, I actually need something like this: type FooMap = {[key: string]: E extends Foo<any>}; ...

What are the steps to set up a dictionary with predetermined values?

My task is to create a pre-defined dictionary where the key represents a city and the value is an array of zones in that city. Here is my attempt: export const cityToZone: { [city: string]: Array<string> } = [ {city:'New York', [&apos ...

You can only import Global CSS from your Custom <App> and not from any other files

Encountered the following error: ./styles/globals.scss Global CSS cannot be imported from files other than your Custom <App>. Due to the Global nature of stylesheets, and to avoid conflicts, Please move all first-party global CSS imports to pages/_ ...

What is the best way to retrieve a string from a URL?

Is there a way to extract only a specific string from a URL provided by an API? For instance: I'm interested in extracting only: photo_xxx-xxx-xxx.png Any suggestions on how to split the URL starting at photo and ending at png? ...

Synchronizing Angular icons with HTML text

Presenting my HTML code <div class="transfer-link" *ngIf="showTransferLink" qa-name="transfer-link"> <a routerLink="/Transfers"> <mat-icon>sync_alt</mat-icon> <div> Transfer </div> ...

Combining multiple arrays into one single array of objects

I've hit a roadblock in my project. It doesn't seem too complicated, but I'm struggling to find the solution right now. Here's the current output I'm getting: Array ( [0] => stdClass Object ( [rel_product_i ...

Before proceeding to update in Angular 8, ensure the repository is not dirty. Commit or stash any changes that have been

Encountered an Issue The repository is not clean. Please commit or stash any changes before updating. When upgrading from version 7 to Angular 8, I faced this error. To find out more about the upgrade process, you can visit the Angular Guide for Upgra ...

The navigate function fails to function properly in response to HttpClient

Hey there! I am facing an issue with the router.navigate function in Angular. When I try to use it within a subscribe method for httpClient, it doesn't seem to work as expected. Can someone please help me understand why this is happening and how I can ...

Retrieve a variety of outputs from computed properties in Vue

I have created buttons to select different dates (one for tomorrow and one for next week) with a function that calculates only business days. The 'tomorrow' button should display either 'Tomorrow' or 'Monday', while the ' ...

Is there a way to programmatically control a Bootstrap Dropdown in Angular?

Need help with opening and closing a Dropdown in my View using my typescript class. Any suggestions on how to achieve this? Appreciate any assistance! <div ngbDropdown class="d-inline-block"> <button class="btn" id=&quo ...

Tips for ensuring that functions interpret the return value of (A | B)[] as equivalent to A[] | B[] in typescript

Upon closer examination, it appears that the types (A | B)[] and A[] | B[] are essentially interchangeable in TypeScript. The evidence for this can be seen in the following examples: var test1: number[] | string[] = [1] var test2: (number | string)[] = [" ...

Dealing with the error: "Error in checking the expression as it has been altered"

I have a dialog form where users can add new projects. I want to prevent the save buttons from being enabled until all required fields are filled in correctly. I have an isValid() function that handles this validation and it appears to be working properly. ...

Production Environment Causing NextJS Website to Malfunction, Development Environment Running Smoothly

While developing an application using NextJS with Typescript, I have come across a unique problem that I have not encountered before. Despite having worked on similar projects and successfully hosting them in the past, this particular issue has me stumped. ...