1

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);

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.