-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
Generic Function with Indexed Type ignores readonly #18374
Comments
You can do so: function mapAssign<T, K extends keyof T>(obj: Readonly<T>, k: K, f: (v: T[K]) => T[K]) {
obj[k] = f(obj[k]); //error
}
type NoChange = {
value: number
}
const obj: NoChange = {value: 5};
mapAssign(obj, "value", x => x+1); |
Note that the solutions I proposed does not affect subtyping or assignability of containing types, only the keys of those types. (Unfortunately, it's in a somewhat backwards incompatible manner). The sample you gave does not resolve the problem. |
My example doesn't solve your problem but mentions that we can use |
The purpose of this issue is to illustrate a case where function modify<T, K extends keyof T>(k: K, x: T, f: (v: T[K]) => T[K]) {
x[k] = f(x[k]);
}
type Point = {
x: number,
y: number,
}
const myConstant: Readonly<Point> = { x: 4, y: 7 };
modify("x", myConstant, x => x + 1);
console.log(myConstant) // => 5 |
Same comment above about backward compatibility applies |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
TypeScript Version: 2.4.2
Code
Expected behavior:
Since
NoChange.value
isreadonly
, it should not be modifiable.Actual behavior:
The code compiles and runs, modifying
obj.value
.This might just be a design limitation that can't be worked around.
If a stricter check was desirable, I could imagine it being something like this:
K extends keyof T
andk: K
andx: T
, thenx[k] = e
would fail, butT = {readonly [k]: any}
would be okayK extends !readonly keyof T
andk: K
andx: T
thenx[k] = e
would succeed, butT = {readonly [k]: any}
would failSo the above program would become
An alternative change (which I think is much less ergonomic) would be the following:
K extends keyof T
andk: K
andx: T
thenx[k] = e
would succeed, butT = {readonly [k]: any}
would failK extends readonly keyof T
andk: K
andx: T
thenx[k] = e
would fail butT = {readonly [k]: any}
would succeed.So the program would be
The text was updated successfully, but these errors were encountered: