Skip to content

Suggestion: Add readonly references to objects & mark readonlyThis methods (pure functions)Β #42758

Open

Description

@emilioplatzer

Suggestion

πŸ” Search Terms

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code.
    • It can or cannot be. It depends on wich name we choose
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Have a way to check readonly object references (including parameters, and this parameter). That allows to check than a function does not modifys an object.

πŸ“ƒ Motivating Example

class Figure{
    constructor (public name: string){}
    checkName(){
        this.name += ' !'
    }
    readonlyMethod logAccess(){
        console.log('one instance of Figure was accesed');
    }
    readonlyMethod safeCheck(){
       // @ts-expect-error
        this.name += ' x'  // this is readonly in a readonlyMethod context
    }
}

function showRO(figure: readonlyReference Figure){
    console.log(figure.name);
    // @ts-expect-error
    figure.name+=" x";  // if figure is a readonly reference you can use it to modify the object
    // @ts-expect-error
    figure.checkName();  // if figure is a readonly reference you can use it to modify the object calling a method
    figure.logAccess();  // ok logAccess is a readonly method
}

var x = new Figure('triangle');

showRO(x);

var z: readonlyReference Figure = x; // ok, you can assign a writeable object to a readonlyReference

// @ts-expect-error
var y: Figure = z ;  // you cannot do the oposite. 

πŸ’» Use Cases

Actually I'am ussing Readonly aproach, but it not contemplates all cases.

play example

I am trying with Object.seal and Proxyies .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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