typescript initialize object with read-only property in-hand

Viewed 1224

Is there a way to initialize an object literal and declare its interface with read-only property in-hand at the same time ?

For example

let a = { readonly b: 2, readonly c: 3 }
2 Answers

You can use a as const assertion:

let a = { b: 2, c: 3 } as const // typed as { readonly b: 2; readonly c: 3; }
a.b = 2 //Cannot assign to 'b' because it is a read-only property.

If you want only some props to be readonly, that is not really possible, best you can do is use an Object.assign with one part containing readonly properties and the other containing the mutable properties:

let a = Object.assign({ b: 2, c: 3 } as const, {
  d: 0
});
a.b = 2 // err
a.d = 1 //ok

you can write it with custom type

type Point = {
  readonly x: number;
  readonly y: number;
};
const a: Point = {
  x: 1,
  y: 2,
};

a.x = 2; // ERROR Cannot assign to 'x' because it is a constant or a read-only property.
Related