6

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 }

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

10 Comments

but you can still change b and c property
No you can not. "Cannot assign to 'b' because it is a read-only property."
@JurajKocan wasn't the point to make the properties readonly ?
@ritaj what ts version are u using? i can still write this a.b = 3 with no error in ts 3.5.1
indeed it works ! I got an error writing a.b = 3. Using typescript 3.4.5
|
0

"as const" is just a compile time error, not runtime error, have to use getter only property.

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

alert(JSON.stringify(a))

FYI, Object.Freeze make whole object can't asssign new propeties

TS Playground, see transformed code, and run it

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.