Skip to content

Suggestion: readonly method #22315

Open
Open
@Conaclos

Description

@Conaclos

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions