Typescript - readonly
TypeScript includes the readonly keyword that makes a property as read-only in the class, type or interface
Since read-only members cannot be changed outside the class, they either need to be initialized at declaration or initialized inside the class constructor
class Employee {
readonly code: number;
name: string;
constructor(code: number, name: string) {
this.code = code;
this.name = name;
}
}
let peter = new Employee(10, "Peter");
peter.name = 'Peter Doan';
peter.code = 20; // Error - TS2540: Cannot assign to 'code' because it is a read-only property.
In the same way you can use Readonly<T> to create a readonly type
type Config = { ENV: string };
const config: Readonly<Config> = { ENV: 'development' };
config.ENV = 'test' // Error TS2540: Cannot assign to 'ENV' because it is a read-only property.
But be careful when use it inside another function with inconsistent type -> readonly property can be changed
type Config = { ENV: string };
const config: Readonly<Config> = { ENV: 'development' };
// config parameter type is Config instead of Readonly<Config>
function doSomething(config: Config) {
config.ENV = 'test';
}
console.log(config.ENV);
// Output: 'test'
You can also use Readonly to make Array or Tuple readonly
type Person = [number, string];
const peter: Readonly<Person> = [10, 'Peter'];
peter.push('Address'); // Error TS2339: Property 'push' does not exist on type 'readonly [number, string]'.