Lesson 14 of 15

Readonly

Readonly

The readonly modifier prevents a property from being reassigned after initialization:

interface Point {
    readonly x: number;
    readonly y: number;
}

const p: Point = { x: 3, y: 4 };
// p.x = 10;  // Error: Cannot assign to 'x' because it is a read-only property

Readonly Arrays

ReadonlyArray<T> (or readonly T[]) prevents mutation:

const nums: readonly number[] = [1, 2, 3];
// nums.push(4);  // Error: Property 'push' does not exist on type 'readonly number[]'
console.log(nums[0]);  // 1

Readonly in Classes

class Config {
    readonly host: string;
    readonly port: number;

    constructor(host: string, port: number) {
        this.host = host;
        this.port = port;
    }

    toString(): string {
        return this.host + ":" + this.port;
    }
}

const cfg = new Config("localhost", 8080);
console.log(cfg.toString());  // localhost:8080
// cfg.port = 9090;           // Error!

Your Task

Define interface Config with readonly host: string and readonly port: number. Write function configString(c: Config): string that returns c.host + ":" + c.port.

TypeScript loading...
Loading...
Click "Run" to execute your code.