Skip to content

API for mutating documents #4212

Answered by yaacovCR
jasonkuhrt asked this question in Q&A
Oct 2, 2024 · 2 comments · 3 replies
Discussion options

You must be logged in to vote

It seems a bit cumbersome to have two versions of the types, so I experimented a bit with some generic types:

interface WithReadOnlyProperties {
    readonly a: string;
}

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

type MutableVersion = Mutable<WithReadOnlyProperties>;

function toMutable<T>(arg: T): Mutable<T> {
    return arg;
}

function toImmutable<T>(arg: Mutable<T>): T {
    return arg;
}

const a: WithReadOnlyProperties = { a: 'a' };

a.a = 'aa'; // Cannot assign to 'a' because it is a read-only property.

(a as Mutable<WithReadOnlyProperties>).a = 'aa'; // Success!

const mutableA = toMutable(a);

mutableA.a = 'aa';

const immutableA = toImmutable(mutableA);

The a…

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
3 replies
@jasonkuhrt
Comment options

@yaacovCR
Comment options

Answer selected by jasonkuhrt
@jasonkuhrt
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants