microsoft / microsoft/TypeScript

Suggestion: readonly method

Open
#22,315 9 comments 61 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Problem:

A method (function written with the ES6 method syntax) can currently be replaced with another function by a simple assignment.

As an example consider the following snippet of code:

class Person {
    constructor(...) {...}
    displayName (): string {...}
}
const x: Person = new Person(...)
x.displayName = function(this: Person): string {...} // Assignment

Because the readonly modifier is not usable for methods, this is not possible to prevent this kind of assignments.

Proposal:

A method is always readonly.

The following codes are identical:

class Person {
    displayName (): string {...}
}
class Person {
    readonly displayName: (this: Person) => string = function () {...}
}

Compatibility:

This is a breaking change. However, method syntax is recent and mostly used in classes. Codes which assign a function to a method are certainly rare.

Temporary workaround:

Do not use method syntax in your classes and interfaces. Note hat this leads to very verbose codes.

If you use an interface, the verbosity is acceptable. However you get also strict variance.

interface PersonI {
    readonly displayName: (this: Person) => string
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No source file or test is named. Start by comparing the class method and readonly property examples in the issue, then trace where TypeScript checks assignments to methods. Done would require a decided readonly-method behavior, compatibility handling for the proposed breaking change, and tests covering assignment rejection.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.