Feature Request: Readonly<T> should remove mutable methods
See original GitHub issueSearch Terms
readonly, as const, Readonly<T>,
Suggestion
Readonly<T> to work the way Readonly<T[]> does without having to create something like ReadonlyArray<T>, ReadonlySet<T>, etc…
I would love it if the Readonly<T>
mapped type could exclude any method marked as readonly
or maybe as cosnt
or something similar.
Use Cases
At the moment I have to do this:
class Vector2 {
public constructor(
public x: number,
public x: number,
) {}
public add(other: ReadonlyVector2): Vector2 {
return this.clone().addInPlace(other);
}
public addInPlace(other: ReadonlyVector2): this {
this.x += other.x;
this.y += other.y;
return this;
}
public clone(): Vector2 {
return new Vector2(this.x, this.y);
}
}
interface ReadonlyVector2 {
readonly x: number;
readonly y: number;
add(other: ReadonlyVector2): Vector2;
clone(): Vector2;
}
This gets very boring with a lot of types, also it’s error prone. I could forget to add something to the interface, or worse I could accidentally add something that is mutable.
I can currently do method(this: Readonly<this>) {...}
, which is helpful, but doesn’t stop me calling mutable methods on the type.
Inside a marked method you would be unable to mutate the state of member variables and you would unable to call other unmarked methods.
This would also allow you to remove the special case of Readonly<T[]>
. The mutable methods of arrays could be marked with whatever syntax is decided and then Readonly<T[]>
would just work like any other Readonly<T>
. Currently I don’t bother using Readonly<T>
since it doesn’t really help with anything except C style POD types.
Examples
class Vector2 {
public constructor(
public x: number,
public x: number,
) {}
public readonly add(other: Readonly<Vector2>): Vector2 {
return this.clone().addInPlace(other);
}
public addInPlace(other: Readonly<Vector2>): this {
this.x += other.x;
this.y += other.y;
return this;
}
public const clone(): Vector2 {
return new Vector2(this.x, this.y);
}
}
Checklist
My suggestion meets these guidelines:
- This wouldn’t be a breaking change in existing TypeScript/JavaScript code
- 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, etc.)
- This feature would agree with the rest of TypeScript’s Design Goals.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:3
- Comments:11 (1 by maintainers)
Top GitHub Comments
Remove all the methods!
How does the compiler know which methods are mutative and which ones aren’t?