Loading...
Loading...
Readonly is a utility type in TypeScript that makes all type properties read-only. After a property becomes readonly, it cannot be changed through direct assignment in code, which helps avoid unintentional object mutations.
Readonly<T>
T — original type whose properties you want to make immutable.The Readonly type is most often used to protect objects from unwanted changes while maintaining read access to their properties.
interface User {
id: number;
name: string;
}
type ReadonlyUser = Readonly<User>;
const user: ReadonlyUser = {
id: 1,
name: "Alice",
};
user.name = "Bob";
// Error: Cannot assign to 'name' because it is a read-only property`
ReadonlyUser turns all properties (id and name) into readonly.Example for immutable configurations:
Sometimes you need to fix settings so they can't be changed after initialization:
interface Config {
readonly port: number; // Already explicitly set
dbName: string;
}
// Using Readonly makes all fields read-only
type FullReadonlyConfig = Readonly<Config>;
const config: FullReadonlyConfig = {
port: 8080,
dbName: "mainDB",
};
config.dbName = "testDB";
// Error: 'dbName' is read-only`
port has readonly, but also dbName becomes readonly when we wrap entire interface in Readonly<Config>.Readonly<T> to prevent accidental changes to passed object:function printUser(user: Readonly<User>) {
// user.id = 42; // Error
console.log(user.id, user.name);
}
readonly property, TypeScript will throw error at compilation stage, helping avoid unintentional mutations.