The debate between using a Class and an Object Literal comes down to the immut

Is it possible to create read-only properties in object literals?

export const Page = {
  
    email: 'input[type=email]',
    password: 'input[type=password]',

    fillLoginCredentials() {
        cy.get(this.email).type('email');
        cy.get(this.password).type('password');
    }

Just to give you a heads up, this is a page object utilized for cypress testing. Although I know how to make these properties immutable using classes, I prefer the simplicity of object literals with static methods.

In general terms, are there any specific advantages to using classes instead?

Answer №1

Utilize Object.freeze() function to secure the object literal during runtime

Check out this straightforward test to verify its effectiveness.

const Task = {
  taskName: 'Buy groceries',
  priority: 'High',
  completeTask() {
      console.log('Completing task: ' + this.taskName);
  }
}

Object.freeze(Task)

it('Properties of Task object cannot be modified', (done) => {
  try {

    Task.priority = 'Low'

  } catch (error) {

    expect(error.message).to.contain("Cannot assign to read only property 'priority'")

    done()          // ensuring execution inside the try/catch block
  }
})

Answer №2

When looking at it through a TypeScript lens, simply incorporating a const assertion will suffice:

export const Page = {
    email: 'input[type=email]',
    password: 'input[type=password]',

    fillLoginCredentials() {
        console.log('Some function');
    }
} as const;

Page.email = ''; // Error
Page.password = ''; // Error
Page.fillLoginCredentials = () => {}; // Error

Playground link

However, be aware that this does not prevent changes during runtime.

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 is preventing TypeScript from recognizing the key property as a component of the Event type?

After creating a function that uses events to determine which button a user pressed by utilizing the event.key property, I encountered an issue. When assigning a type Event as a parameter for the function, the compiler generates an error message stating th ...

TypeScript feature: Determining return type dynamically based on object property using string literal

I am looking to enhance the functionality to dynamically determine the return type based on the string literal provided. Current Approach: type Baseball = { name: string; lng: number; lat: number; } type SeriesInfo = { series: { [key: string]: ...

Converting TypeScript into a single line of PHP code

Currently, I am in the process of translating a TypeScript code snippet to PHP, and things are progressing well so far. However, I have come across some one-liners in TypeScript that I am having trouble translating accurately. Here is the TypeScript code ...

Enhancing Angular 5 with CustomEvent Polyfill for JavaScript

After implementing the code snippet in main.ts file, I encountered an issue with CustomEvent not being added to the window object correctly. Strangely, when I manually add CustomEvent using the JavaScript console, it works fine. This problem arises specifi ...

Tips for defining the anticipated server response solely based on status and cookie

I am using Redux Toolkit Query to occasionally refresh the jwt token: import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"; export const refreshApi = createApi({ reducerPath: "apiSlice", baseQuery: fetchBaseQuer ...

Ensuring that files adhere to the required format, whether they be images

Three separate input fields are being used, each with its own name for identification. A validation method is called to ensure that the files selected in these input fields are not duplicates and that they are either images or PDFs but not both. While thi ...

What's wrong with the current longitude and latitude bounding box algorithm used for geolocation searches?

I am currently working on a piece of code that calculates a bounding box for a specific location to search for user profiles within a given radius. The code is mostly functional, but I am encountering a slight distortion in the final values. When I input 5 ...

This object does not have support for the attribute or method "getAttribute"

I've searched for solutions, but nothing seems to work for me and now I'm feeling quite lost. My current setup involves Cordova, Ionic, and Angular 2. Below is the HTML snippet: <ion-col *ngFor="let value of myButtonsFirstRow" width-25> ...

What is the best method for retrieving database table content in NestJS?

In MySQL, I successfully created a database named refy with a single table labeled app. https://i.sstatic.net/BI8VD.png My current focus is on utilizing NestJS to retrieve all columns from the mentioned table: import { Controller, Get } from '@nestj ...

Matching TypeScript search field names with column names

Seeking ways to create an API that allows admins to search for users in the database using various fields. // Define allowed search fields type SearchFieldType = 'name' | 'memberNo' | 'email' | 'companyName'; const ...

Is there a way to locate a prior version of the NPM @types package?

Currently, I am utilizing Angular version 1.4.7 and in need of a type file corresponding to this specific version. Browsing through the NPM website, I came across a type file for AngularJs listed as version 1.5.14 alpha. Is there a way to access a compreh ...

Is it possible to use both interfaces and string union types in TypeScript?

My goal is to create a method that accepts a key argument which can be either a string or an instance of the indexable type interface IValidationContextIndex. Here is the implementation: /** * Retrieves all values in the ValidationContext container. ...

Ways of utilizing a dynamic key for invoking a resource from prisma

Currently, I am attempting to implement a more general method to retrieve data from Prisma. The function in question appears as follows: import { Prisma, PrismaClient } from '@prisma/client'; import { NextApiRequest, NextApiResponse } from ' ...

Steps for developing a versatile function Component

Can I create generic function components? I thought that the following example would work: type MyComponentProps<T> = T & { component: ComponentType<T>, primary?: boolean, size?: 'S' | 'M' | 'L' ...

Converting TypeScript into JavaScript files within an ASP.NET SPA application

As I work on my current project using ASP.NET spa and Vue.js, I have been serving the dist folder from the Vue.js client app statically. This dist folder contains the compiled result of the client app's /src directory, where all .Vue and .ts files are ...

How can one correctly cast or convert an array of objects to the interface that extends the objects' parent interface in Typescript?

Question: How can I optimize the usage of method sendItemIdsOverBroadcastChannel to reduce message size? interface IItemId { id: number; classId: number; } interface IItem extends IItemId { longString: string; anotherLongString: string } inte ...

Encountering TS2304 error message while running TypeScript files indicates the inability to locate the name 'PropertyKey', in addition to another error - TS2339

I encountered an issue while attempting to execute a spec.ts file in the Jasmine Framework. After installing @types/core-js version 0.9.46 using the command npm i @types/core-js, I started receiving the following error messages: > ../../node_modules/ ...

Exploring techniques to retrieve data from Json Array in Angular using Firebase documentation

this.currentUser$=this.afs.doc('users/'+this.authState.uid).valueChanges().pipe(); When I include it in my component.html file like this: {{ currentUser$|async|json}} The output I get is as follows: { "photoUrl": "", &qu ...

The v8 getHeapShot function is causing an infinite hang in jest

I am currently facing a memory leak issue in my code and I am attempting to troubleshoot it by generating a heap snapshot using the Nodes v8 library. I am developing an endpoint in typescript with express that can be invoked to retrieve a JSON object, whic ...

What are the downsides of utilizing a global function over a private static method in Typescript?

It's quite frustrating to have to write this.myMethod() or ClassName.myMethod() instead of just myMethod(). Especially when dealing with a stateless utility function that doesn't need direct access to fields. Take a look at this example: functi ...