const vs readonly
Written byPhuoc Nguyen
Category
TypeScript
Created
20 Aug, 2020
#Differences
-
`const`
is used for variablesconst message = 'Hello';// Does not workmessage = 'World';While`readonly`
is used for properties. The properties can be declared as a member of classclass Triangle {public readonly numberOfVertices = 3;}const triangle = new Triangle();// Does not worktriangle.numberOfVertices = 4;or`type`
,`interface`
:interface Person {firstName: string;lastName: string;readonly fullName: string;} -
`const`
declarations have to be initialized, and you can't reassign their values. The`readonly`
properties can be reassigned in the constructor function.class Square {readonly numberOfVertices: number;constructor() {this.numberOfVertices = 4;}}The`readonly`
properties could be changed if we don't pass their class or interface directly but passing an alias.Let's take a look at the`Person`
interface above, and assume that we have the following function to update the person information:const updatePerson = (person: { firstName: string, lastName: string, fullName: string }) => {person.fullName = `\${firstName}, \${lastName}`;};We can update the`fullName`
property because it's an property of`person`
parameter:let person: Person = {firstName: 'Foo',lastName: 'Bar',fullName: 'Foo Bar',};updatePerson(person);person.fullName; // `Foo, Bar`Of course, the compiler will throw an error if we pass the original type`Person`
:const updatePerson = (person: Person) => {// Error: Cannot assign to 'fullName' because it is a read only propertyperson.fullName = `\${person.firstName}, \${person.lastName}`;};
#Good to know
-
In a given class, if a property has only getter method and doesn't come with setter method, it will be treated as read only.class Square {side: number = 0;get area() {return this.side * this.side;}}const s = new Square();Setting
`s.area = 100`
will throw an error because`area`
is a ready only property. -
In the React library, we don't change the props and state of a component directly. Because the props are immutable and the state could be updated via
`setState()`
method.React type definitions wrap the props and state in read only type.// P, S represents the props and state respectivelyclass Component<P, S> {constructor(props: Readonly<P>);readonly props: Readonly<P> & Readonly<{ children?: ReactNode }>;state: Readonly<S>;}
Questions? 🙋
Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.
Recent posts ⚡
Copy the content of an element to your clipboard
01 Oct, 2023
Make a text area fit its content automatically
30 Sep, 2023
Quickly insert alternate characters while typing
30 Sep, 2023
Zebra-like background
30 Sep, 2023
Add autocomplete to your text area
28 Sep, 2023
Linear scale of a number between two ranges
28 Sep, 2023
Highlight the current line in a text area
27 Sep, 2023
Create your own custom cursor in a text area
27 Sep, 2023
Mirror a text area for improving user experience
26 Sep, 2023
Display the line numbers in a text area
24 Sep, 2023
Select a given line in a text area
24 Sep, 2023
Newsletter 🔔
If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn