-
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
Object.freeze after object creation doesn't error #32253
Comments
If this is an intentional design decision, it would be a good candidate for documentation on microsoft/TypeScript-Handbook#1059 |
Typescript has no way to model the fact that a simple method call changes the type of its parameter. The only way to model such changes are custom type guards, and these have to be used in some sort of conditional to work: function freezeAndGuard<T>(p: T): p is Readonly<T> {
Object.freeze(p);
return true;
}
(function () {
const b = {b: 0};
if(!freezeAndGuard(b)) return;
b.b = 1; // Err
const c = {c: {d: 0}};
if(!freezeAndGuard(c.c)) return;
c.c.d = 1; // Err
})(); |
Thanks for the answer! I suppose we can tag this as "Working as Intended" or similar and close it then? In any case, good to have this documented at least here. Maybe also good to add to the handbook, maybe one or multiple of the following:
|
Would also be interested: is this a design limitation of TypeScript? Is there a possibility of changing it? It feels like it would not be a small change... |
There were several proposals to implement something like custom type assertion ( #10421, #31512, #31879, #17760, #32130 just to name a few). It feels small but it actually has big performance implications. From previous comment:
|
Thanks for the detailed explanation! Really helpful to have this all linked together 🙌 |
I actually meant to say "not a small change", but I think the |
currently wish i could refactor this: export class JSXIdentifier {
readonly type: string;
readonly name: string;
constructor(name: string) {
this.type = JSXSyntax.JSXIdentifier;
this.name = name;
}
} into this: export class JSXIdentifier {
type: string;
name: string;
constructor(name: string) {
this.type = JSXSyntax.JSXIdentifier;
this.name = name;
Object.freeze(this);
}
} |
TypeScript Version: 3.5.1
Search Terms: Object.freeze, freeze, freezing, properties, object, objects, property
Code
Expected behavior:
Cannot assign read-only property
errors for the two lines with "No error?" above.Actual behavior:
No errors
Playground Link: https://www.typescriptlang.org/play/?removeComments=true#code/MYewdgzgLgBAhjAvDA8gIwFYFNhQHQBmATllgF5YAUA3nAFwwAMAvgJQDcAUHHgsgIzsYAemEwAokSIgiDAMJwwYELDgQIASwDmYGCTgATALTgANgE8YAB2lWsRKOc6dQkWGiQxqaBiy7psXEIScio0Dk40PA8BIVEYADkQGHtpIgB+Z1doGGBPamAGagNfZmZ-TBx8YlIKSmA8YAiGhoNPQRExJJSpGXSgA
The text was updated successfully, but these errors were encountered: