3 min read
•Question 9 of 48easyWhat is readonly in TypeScript?
Creating immutable properties.
What You'll Learn
- readonly keyword
- Readonly utility type
- const vs readonly
readonly Keyword
code.tsTypeScript
interface User {
readonly id: string;
name: string;
}
const user: User = {
id: "123",
name: "John"
};
user.name = "Jane"; // OK
user.id = "456"; // Error: Cannot assign to 'id'Readonly Arrays
code.tsTypeScript
const numbers: readonly number[] = [1, 2, 3];
numbers.push(4); // Error
numbers[0] = 10; // Error
// ReadonlyArray type
const items: ReadonlyArray<string> = ["a", "b"];Readonly Utility Type
code.tsTypeScript
interface Config {
host: string;
port: number;
}
const config: Readonly<Config> = {
host: "localhost",
port: 3000
};
config.port = 8080; // Error: all properties readonlyconst vs readonly
code.tsTypeScript
// const: variable cannot be reassigned
const x = 10;
x = 20; // Error
// readonly: property cannot be modified
interface Point {
readonly x: number;
}