-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add a constraint for immutable types #14909
Comments
|
i was talking about special generic constraints that would guarantee that a type argument is immutable what did you mean by interface Writable {
value: string;
}
function willOnlyTakeReadonly<T>(data: Readonly<T>): void {
}
declare const writable: Writable ;
willOnlyTakeReadonly(writable); // <-- no problem i am afraing it doesn't work at least in the latest version of TS, because anything can be used in place of |
@Aleksey-Bykov you can't mutate the input though type Writable = {
value: string
}
function willOnlyTakeReadonly(data: Readonly<Writable>): void {
data.value = 'a' // error Cannot assign to 'value' because it is a constant or a read-only property
}
declare const writable: Writable
willOnlyTakeReadonly(writable) |
not sure I understand then, what did you have in mind constraining the Input? |
i added 2 use cases that shed some light on when/why it is useful to constrain the input |
any reason why it was closed? |
I support the goals of this proposal. Some design issues:
function doThings<T>(value: immutable T): Result<T> {
// ...
} but additionally having an
immutable {a: 1, b: 2}
immutable [3, 4, 5]
immutable new MyPair(point1, point2) To use the same constructor to construct both mutable and immutable objects, we need to make it polymorphic in whether the new object is mutable. I.e., we think of the presence or absence of the |
say, i have a generic function that by design requires that its parameters may only take immutable arguments, i wish i could get such guarantee from TS by declaring my function as follows:
as far as how to make an interface immutable:
so the problem being solve here is to make sure that the caller won't mutate the argument after it is passed to the function
simple use case: a hash-based data container, which calculates a hash of a given value, and will store it at that hash, and it all will work until the value is mutated outside and tha stored hash is no longer valid, so the container doesn't really work anymore
another use case: a cache or object pool or any other situation when there are many parties involved in taking hold of the same object, which must be guaranteed from being mutated by one party to prevent spooky action at a distance for all other parties
The text was updated successfully, but these errors were encountered: