Reputation: 425
I'm looking for a way to mark an object literal's property as readonly. So that the following code would produce a compilation error:
const o = {
p: true
};
o.p = false; // <== i want an error here
I obviously can do it like this:
const o: {readonly p: boolean} = {
p: true
};
o.p = false;
But this is really clumsy.
Is there any more elegant way?
Upvotes: 1
Views: 200
Reputation: 249466
If you want to make all properties readonly as const
is a good option:
const o = {
p: true
} as const;
o.p = false;
If you want only some properties to be readonly, there isn't a good option ... Object.assign
works but is rather clunky:
const o = Object.assign({
nonRo: true
}, {
p: true
} as const);
o.p = false;
o.nonRo = false //ok
Upvotes: 1