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;
Of course, the compiler will throw an error if we pass the original type Person
:
const updatePerson = (person: Person) => {
person.fullName = `\${person.firstName}, \${person.lastName}`;
};