Aravind
Aravind

Reputation: 41581

Difference between const and readonly in typescript

Constant vs readonly in typescript

Declaring a variable as readonly will not allow us to override even if they are public properties.

How const behaves,

const SOME_VARIABLE:number = 10;

If I override its value, how will it work?

Upvotes: 145

Views: 104075

Answers (7)

niranjan_harpale
niranjan_harpale

Reputation: 2274

One of the key difference between const and readonly is in how it works with the array (apart from differences mentioned in other answers). You have to use

readonly Array<T> 

while working with Array, where T is generic type(google it for more).

when you declare any array as const, you can perform operations on array which may change the array elements. for ex.

const Arr = [1,2,3];

Arr[0] = 10;   //OK
Arr.push(12); // OK
Arr.pop(); //Ok

//But
Arr = [4,5,6] // ERROR

But in case of readonly Array you can not change the array as shown above.

arr1 : readonly Array<number> = [10,11,12];

arr1.pop();    //ERROR
arr1.push(15); //ERROR
arr1[0] = 1;   //ERROR

Upvotes: 48

KZTN
KZTN

Reputation: 5

const

  1. constant in compile time
  2. must be initialized on its declaration
  3. can be declared in methods

readonly

  1. constant in execution time
  2. don't need to be initialized on its declaration
  3. can't be declared in methods, only constructor or self declaration

Upvotes: -1

Nir Alfasi
Nir Alfasi

Reputation: 53565

  1. I think that the accepted answer didn't emphasized enough that const is expected to be used with variables while readonly with class/interface properties.

  2. readonly is checked only during type-checking (compile time) while const is checked during runtime

  3. declaring a property to be readonly doesn't mean that its value can't be changed: it means that the property cannot be re-assigned, example:


interface Person {
    readonly info: { name: string; age: number };
}

//create a new person
// ...

person.info.age += 1; // this is valid
person.info = { name: "Johnny", age: 15 }; // this is invalid!
  1. Since TS 3.4 there are const assertions which are used to define types:

// Type 'readonly [10, 20]'
let y = [10, 20] as const;

// Type '{ readonly text: "hello" }'
let z = { text: "hello" } as const;

For more, see the docs

Upvotes: 18

user1660210
user1660210

Reputation: 2852

both:

  • can be changed (for example by .push() if array)

const:

  • can't be reassigned
  • used for variables

readonly:

  • can be reassigned but only inside constructor
  • used for properties (class member)

Upvotes: 21

Greg
Greg

Reputation: 61

I think the reason for both words is probably that it's easier to implement than the alternative.

In C++, for instance, classes can have const members. But C++ has special syntax to initialize the constants before the constructor is run, so there's never really any "assignment" to the const going on, like:

class TestClass {
    const int _x;
    TestClass(int x) : _x(x) {}
}

The _x(x) initializes the _x variable before the constructor is called.

In Typescript, if they wanted to allow members to be declared const and were serious about the variables being const, they would need to add similar syntax.

"readonly" isn't really the same as const. It means, I think, something slightly different. It means "allow assignment inside the constructor, but then no more."

Upvotes: 1

Stef
Stef

Reputation: 203

as said in https://www.typescriptlang.org/docs/handbook/interfaces.html#readonly-vs-const

The easiest way to remember whether to use readonly or const is to ask whether you’re using it on a variable or a property. Variables use const whereas properties use readonly.

as it displayed in below image if you declare const in defining a property you will get an error https://i.sstatic.net/9SFHm.png

Upvotes: 8

Fenton
Fenton

Reputation: 251262

A const variable cannot be re-assigned, just like a readonly property.

Essentially, when you define a property, you can use readonly to prevent re-assignment. This is actually only a compile-time check.

When you define a const variable (and target a more recent version of JavaScript to preserve const in the output), the check is also made at runtime.

So they effectively both do the same thing, but one is for variables and the other is for properties.

const x = 5;

// Not allowed
x = 7;


class Example {
    public readonly y = 6;
}

var e = new Example();

// Not allowed
e.y = 4;

Important note... "cannot be re-assigned" is not the same as immutability.

const myArr = [1, 2, 3];

// Not allowed
myArr = [4, 5, 6]

// Perfectly fine
myArr.push(4);

// Perfectly fine
myArr[0] = 9;

Upvotes: 165

Related Questions