CodeBlanks Logo Icon CodeBlanks

Readonly properties

Learn immutable properties with readonly.

Readonly properties

To make object properties immutable, you write readonly before the property name. Once set, a readonly property cannot be changed.

let kisi: { readonly id: number; ad: string } = {
  id: 1,
  ad: "Ali"
};

readonly prevents the property from being modified later.

Using readonly properties

Readonly properties are suitable for values that should never change, such as identifiers or codes. Attempting to assign to a readonly property causes a compile error.

let kisi: { readonly id: number } = { id: 1 };
kisi.id = 2;  // error: readonly

Readonly prevents accidental modification at compile time.

Practice Object with a readonly property

Declare a variable named urun with type { readonly kod: string; fiyat: number } and value { kod: "A100", fiyat: 50 }. Print the value of urun.kod with console.log.

Starter code

index.ts
// urun adında bir nesne tanımla
// kod özelliği readonly dize, fiyat özelliği sayı olsun
// kod değeri "A100", fiyat değeri 50 olsun
// urun.kod değerini yazdır

Sample solution

index.ts
let urun: { readonly kod: string; fiyat: number } = { kod: "A100", fiyat: 50 };
console.log(urun.kod);

Expected output

A100

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>readonly id: number</code> indicate?

  • id property is of type string
  • id property can be any type
  • id property is optional
  • id property cannot be changed after creation Correct answer

Explanation: <code>readonly</code> indicates that the property cannot be changed after the first assignment; <code>id</code> cannot be reassigned once created.

2 Make the property readonly

Question
let kullanici: { ____ id: number; ad: string } = { id: 1, ad: "Ali" };
Answer
let kullanici: { readonly id: number; ad: string } = { id: 1, ad: "Ali" };

Explanation: To make a property immutable, the <code>readonly</code> keyword is written before the property name; <code>let</code>, <code>const</code> and <code>static</code> are not used as property modifiers.

3 Readonly property concepts

Term Meaning
readonly id: number Immutable id property
id: number (readonly yok) Mutable id property
readonly (özellik önünde) Makes a property fixed
Readonly property Cannot be reassigned later

All lessons in Beginner