Dmytro Gokun
Dmytro Gokun

Reputation: 425

Specify that an object literal's property is readonly

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

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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; 

Playground Link

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

Playground Link

Upvotes: 1

Related Questions