Differences between a readonly variable and a method with a readonly type in TypeScript

Exploring the Contrast Between Readonly Variables and Readonly-Typed Methods in TypeScript

Readonly Variable:

maxLength: Readonly<Number | number | String | string> = 1;

vs

Readonly-Typed Method:

maxLength(length: Number | number | String | string): Readonly<Number | number | String | string> {
        var width: Readonly<Number | number | String | string> = length;
        return width;
    }
  • What separates these two concepts?
  • Can values be assigned to a Readonly function at runtime?

Answer №1

Readonly<T> defines an object-type mapping:

type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};

This feature ensures that all properties of object T are made read-only to the compiler - which means it is not suitable for use with primitive types like number or string since they do not have properties.

If you require a property that is read-only externally but can be changed internally at runtime, consider using a getter method.

interface IFoo {
  readonly length: number;
}

class Foo implements IFoo {
  private _length: number;

  get length(): number {
    return this._length;
  }

  change(length: number) {
    this._length = length;
  }
}

There is no functional difference between a variable with type Readonly<T> and a method that returns a variable with type Readonly<T>, except for the additional step of using a method.

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

Ways to clear an Angular form after a failed login attempt

Looking for a solution to reset the input fields used to store login PIN from a user. My current code generates a modal error message but I am facing an issue in resetting the PIN input fields under the #inputs id. Take a look at the code snippet below: H ...

What location is most ideal for incorporating JavaScript/Ajax within a document?

Sorry for the seemingly simple question, but I would appreciate some clarification from the experts. When it comes to the three options of placing JavaScript - head, $(document).ready, or body, which would be the optimal location for ajax that heavily rel ...

Is it possible to animate the innerHTML of a div using CSS?

In my HTML file, I have these "cell" divs: <div data-spaces class="cell"></div> When clicked, the innerHTML of these divs changes dynamically from "" to "X". const gridSpaces = document.querySelectorAll("[data-spaces]"); f ...

MikroORM - Conditional join without foreign key constraints on the ID

I came across a rather peculiar database schema that includes a jsonb field with userId and userType attributes, along with two different user tables for distinct user types. The selection of the table to join based on the userType is crucial. Although I ...

In the world of React in Meteor, the command event.preventDefault() doesn't seem

I have encountered an issue with my application development. I am utilizing a submit form in Meteor with React, and although I am using event.preventDefault(), the page continues to reload every time the submit button is clicked. Following a brief delay, i ...

Employ node's gm library in combination with promises and buffers

Using gm with Bluebird has been a bit tricky for me. Initially, I tried this approach: var gm = require('gm'); var bluebird = require('bluebird'); gm = bluebird.promisifyAll(gm); However, when attempting to execute the following code: ...

What is the reason behind the perpetual hiding of the button?

<div class="app__land-bottom" v-if="isVisible"> <a href="#projects"> <img ref="arrowRef" id="arrow" src="./../assets/down.png" alt srcset /> </a> </div> When ...

Retrieving URL from AJAX Request in Express JS

Currently, I am in the process of developing an Express App and encountering a challenge regarding the storage of the user's URL from which their AJAX request originated. In simpler terms, when a website, such as www.example.com, sends an HTTP request ...

What is the right way to utilize Fetch in JavaScript and Django?

I am currently working on creating a METAR decoder similar to the one shown in this image: https://i.stack.imgur.com/P40uG.png For this project, I am implementing the use of the fetch function in Vanilla JavaScript. The goal is to send the inputted code t ...

Executing multiple HTTP requests in Angular using the HttpClient

Recently, I came across a concerning issue in my Angular 5 App. It all started with this simple call in my service: interface U{ name:string; } ... constructor(private http : *Http*, private httpC:HttpClient) // Http is deprecated - its a compare test ...

Custom JSON filtering

I have a JSON object called Menu which contains various menu items for my system that I am developing using VueJS + Vuetify. I need to filter these menu items based on the "text" field, regardless of position in the text and without differentiating between ...

Use jQuery to display the user input value in real-time

I am in the process of developing a dynamic calculation program to sharpen my jQuery skills, but unfortunately, I'm facing some challenges. I have managed to store values in variables as shown in the code snippet below. <form> Table of: ...

Enhancing AngularJS view rendering using ngshow

Currently, I am working on a view where ng-show is used to display a select DOM object when certain conditions are met, and an input DOM for all other scenarios. However, I have noticed that there is a significant delay in the disappearance of the input bo ...

The custom function is not compatible with any of the available overloads

I'm setting up an event listener that triggers a function to update the state when the event occurs. import React, {useState, useRef, useLayoutEffect} from 'react'; const [width, setWidthIn] = useState<number>(0) const ref = useRef< ...

Display or conceal elements in Angular based on multiple conditions

Looking to develop a functionality where an array of objects can be shown or hidden based on specific filters. The desired output should be as follows: HTML CODE: Filter: <div (click)="filter(1)"> F1 </div> <di ...

Function execution in React component is not happening

Trying to master React and next.js with Firebase as the database has been an interesting journey. I recently encountered an issue where a function in my component is not being called. Upon trying to debug using console.logs(), it appears that the function ...

The Jade variable assignment variable is altered by the Ajax result

Seeking a solution to update a Jade variable assigned with the results of an ajax post in order for the page's Jade loop to utilize the new data without re-rendering the entire page. route.js router.post('/initial', function(req, res) { ...

Issue encountered when attempting to make a global call to an asynchronous function: "The use of 'await' is restricted to async functions and the top level bodies of modules."

As I embark on solving this issue, I want to point out that while there are similar questions on SO based on the title, upon close examination, they seem more intricate than my specific situation. The explanations provided in those threads do not quite ali ...

Dispatching actions in `componentDidMount` is restricted in Redux

Update at the bottom of post I've created a React container component called AppContainer, which checks if the user is authenticated. If the user is authenticated, it renders the app's routes, header, and content. If not, it displays a Login com ...

Updating an SVG after dynamically adding a group with javascript: a step-by-step guide

Currently, I am working on a circuit builder project using SVG for the components. In my HTML structure, I have an empty SVG tag that is scaled to full width and height. When I drag components from the toolbar into the canvas (screen), my JavaScript functi ...