csb00
csb00

Reputation: 1155

Immutable Data with Readonly in TypeScript

In my quest to learning TypeScript, I am currently reading about Immutable Data with Readonly in TS. I know what the code below is supposed to do, which is return 0 and "1". I am confused tho as to what exactly type ReadonlyInterface<T> and function genericInterfaceToReadOnly<T> are suppose to be doing. Can somebody please explain?

interface OriginalInterface {
    x: number;
    y: string;
}

type ReadonlyInterface<T> = { readonly [P in keyof T]: T[P] };

function genericInterfaceToReadOnly<T>(o: T): ReadonlyInterface<T> {
    return Object.freeze(o);
}

const original: OriginalInterface = { x: 0, y: "1" };
const originalReadonly = genericInterfaceToReadOnly(original);

Upvotes: 1

Views: 536

Answers (1)

Aplet123
Aplet123

Reputation: 35482

The ReadonlyInterface type uses the mapped type syntax to create a generic which turns all of the properties in the type parameter into read-only parameters. Note that this is equivalent to the built in ReadOnly type. So, in this case, ReadonlyInterface<OriginalInterface> would be:

interface OriginalInterface {
    readonly x: number;
    readonly y: string;
}

Marking the properties as readonly in the type level. The genericInterfaceToReadOnly takes an object of type T, and returns a readonly version of it by using Object.freeze, which makes the object immutable at runtime as well. Essentially, the type combined with the function allow you to make a value immutable in both the type and runtime levels.

Upvotes: 1

Related Questions