What about a toggle for read-only TypeScript everywhere? (parameters in functions)

Is there a method, whether through a macro library, an eslint rule, a tsconfig setting, a special global.d.ts file, or some other means, to automatically set function arguments as readonly by default?

// I wish for the compiler to transform this:
function foo(a: A[], b: Record<string, string>) {
}
// Into this
function foo(a: ReadonlyArray<A>, b: Readonly<Record<string, string>>) {
}

Answer №1

Take a look at the no-param-reassign ESLint rule:

The main goal of this rule is to prevent unintended consequences that may arise from altering or assigning new values to function parameters.

It's important to note that this rule doesn't serve as a replacement for using readonly:

/* eslint no-param-reassign: ["error", { "props": true, "ignorePropertyModificationsForRegex": ["^mut"] }] */
function f(n: number, nums: number[], o: { p: string }, mutArr: number[]) {
    n = 10 // will result in an error
    n++ // will result in an error
    for (n in nums) { } // will result in an error
    nums[1] = 10 // will result in an error
    nums.push(1) // will pass
    nums.sort() // will pass
    o.p = 'foo' // will result in an error
    mutArr[0] = 10 // will pass
}

Answer №2

An ongoing discussion in the typescript github repository is centered around a feature request similar to this:

https://github.com/microsoft/TypeScript/issues/62941

The issue of handling untyped library code seems to be a major concern, which may delay the decision on implementing this feature.

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

There seems to be a lack of information appearing on the table

I decided to challenge myself by creating a simple test project to dive into Angular concepts such as CRUD functions, utilizing ngFor, and understanding HttpClient methods (specifically get and post). After creating a Firebase database with an API key and ...

Querying with a TypeORM many-to-many relationship

Entity Program: export abstract class ProgramBase { @Column('varchar') programName: string; @Column('text') programDescription: string; @Column({ type: 'boolean', default: false }) isDeleted: boolean; @Column( ...

Contact the help desk and receive information that is currently unknown

There are a few issues that I'm struggling to resolve. I am utilizing SwaggerService to fetch data, but the response is coming back as undefined. import {SwaggerService} from '../../services/swagger.service'; export class TestComponent im ...

Error message when using Typescript with Redux Saga: "Cannot use 'then' property on type 'void'. TS2339"

Whenever I attempt to fetch data from this API endpoint using promises, I encounter these type of issues. export function* signUpWithEmail(authInfo: any) { const { email, password } = authInfo.payload try { const response = yield authSignUpService ...

Guide to setting up a one-to-many self relation entry in Prisma

I am facing a challenge with a simple schema model that includes one-to-many self relations. In this scenario, my goal is to create a parent entity along with its children in a single transaction. How can I accomplish this task effectively? data-model Y{ ...

User interaction with a checkbox triggers a state change in Angular

Here is the code snippet I am working with, where clicking should set the checked value to false: @Component({ template: ` <input type="checkbox" [checked]="checked" (change)="onChange()"> ` }) export class AppC ...

What is the best way to utilize the next-env.d.ts file within Next.js?

In my Next.js TypeScript project, I came across a file named next-env.d.ts. This got me thinking about how I can declare enums that would be accessible across all my Next.js files. Can you guide me on how to achieve this and use the enums throughout my p ...

Exploring Mikro-ORM with Ben Awad's Lireddit: Navigating the Process of Running Initial Migrations

Having some trouble following the lireddit tutorial, particularly with the initial mikro-orm migration step. Encountering a similar issue as mentioned in this post. Tried modifying the constructor of the example entity (tried both provided format and the ...

Unable to find solutions for all parameters needed by a CustomComponent within Angular

Whenever I attempt to compile the project for production, an error pops up: There is a problem resolving all parameters for EmployeeComponent in C:/.../src/app/employee/employee.component.ts: (?, ?, ?). Oddly enough, when I run the application, every ...

Creating a TypeScript library with Webpack without bundling may seem like a daunting task, but

Currently, I am developing a React component package using Typescript and NPM. During my research, I discovered that generating individual .js and .d.ts files is more beneficial than bundling them into one bundle.js file. However, I am facing difficulty in ...

What is the mechanism behind Typescript interface scope? How can interfaces be defined globally in Typescript?

I'm diving into the world of Typescript and Deno, but I'm struggling to understand how interfaces scopes work. Here's the structure of my application: The first layer (App.ts) contains the core logic of my application. This layer can refer ...

How to dynamically disable a checkbox in Angular reactive forms depending on the value of another checkbox

I am attempting to deactivate the checkbox based on the value of other checkboxes. Only one of them can be activated at a time. When trying to activate one of the checkboxes, I encounter an issue where the subscribed value is being repeated multiple times ...

Creating a ref with Typescript and styled-components: A comprehensive guide

Trying to include a ref into a React component looks like this: const Dashboard: React.FC = () => { const [headerHeight, setHeaderHeight] = useState(0); const headerRef = React.createRef<HTMLInputElement>(); useEffect(() => { // @ts ...

When delving into an object to filter it in Angular 11, results may vary as sometimes it functions correctly while other times

Currently, I am working on implementing a friend logic within my codebase. For instance, two users should be able to become friends with each other. User 1 sends a friend request to User 2 and once accepted, User 2 is notified that someone has added them a ...

The issue of not displaying the Favicon in Next.js is a common problem

I am currently using Next.js version 13.4.7 with the App directory and I am facing an issue with displaying the favicon. Even though the favicon image is located in the public folder and in jpg format, it is not being displayed on the webpage. However, w ...

Ways to dynamically generate a generic that expands a union class type

Reviewing the code snippet: const events = { a: ['event1' as const, 'event2' as const], b: ['event3' as const, 'event4' as const], }; class SomeClass< T extends AnotherClass<typeof events[keyof typeof ev ...

Encountering a TypeScript issue with bracket notation in template literals

I am encountering an issue with my object named endpoints that contains various methods: const endpoints = { async getProfilePhoto(photoFile: File) { return await updateProfilePhotoTask.perform(photoFile); }, }; To access these methods, I am using ...

Why does TypeScript keep throwing the "No inputs were found in the config file" error at me?

Why am I receiving the No inputs were found in config file error from TypeScript? I have set up my tsconfig.json in VS Code, but the error occurs when I try to build it. The terminal displays: error TS18003: No inputs were found in config file '/Use ...

The module '@angular/core' could not be located in the '@angular/platform-browser' and '@angular/platform-browser-dynamic' directories

Attempting to incorporate Angular 2.0.0 with JSMP, SystemJS, and TS Loader in an ASP.NET MVC 5 (non-core) application. Encountering errors in Visual Studio related to locating angular modules. Severity Code Description Project File Line Suppr ...

It appears that protractor-flake is programmed to re-run all tests instead of just the ones that have failed

Running tests using the latest version of "[email protected]", encountering failures during testing but the tests are rerunning again. No custom reporter used except Allure reporting. Below is the command used for running: protractor-flake --max-at ...