/ Gists / Utility type: Readonly
On gists

Utility type: Readonly

Typescript

index.ts Raw #

/*
Readonly je utility typ v TypeScriptu, 
který změní všechny vlastnosti daného typu na pouze pro čtení (readonly)

Readonly<T>
*/

// 1
interface User {
    id: number;
    name: string;
    email: string;
}

const user: Readonly<User> = {
    id: 1,
    name: 'Alice',
    email: 'alice@example.com',
};

// Pokus o změnu vlastnosti způsobí chybu
user.name = 'Bob'; // Error: Cannot assign to 'name' because it is a read-only property.

// 2
interface Config {
    apiEndpoint: string;
    timeout: number;
}

const config: Readonly<Config> = {
    apiEndpoint: 'https://api.example.com',
    timeout: 3000,
};

// Tento pokus o úpravu způsobí chybu:
config.timeout = 5000; // Error: Cannot assign to 'timeout' because it is a read-only property.