How can I change a readonly property in TypeScript?

后端 未结 6 1947
眼角桃花
眼角桃花 2021-01-04 02:43

I want to be able to make readonly properties (not getters) for users of my class, but I need to update them internally; is there a way to do this and allow to

6条回答
  •  轮回少年
    2021-01-04 03:28

    You could make use of the improved mapped type modifiers since Typescript 2.8.

    For example, let's say that UI layer (and all others except persistence layer) shall only get a readonly version of your domain entity. Persistence layer is a special case, since it somehow must know how to copy all internals into the database. In order to do so, we don't want to make defensive copies everytime and just use the readonly typescript modifier for that purpose.

    Your readonly entity would be:

    class Immutable {
        constructor(
            public readonly myProp: string ) {}
    }
    

    The mutable type of your entity:

    type Mutable = {
         -readonly [K in keyof Immutable]: Immutable[K] 
    }
    

    Note the special -readonly syntax to remove the flag (also works with optionals).

    In one limited place (here the persistence layer) we can convert Immutable to Mutable by doing:

    let imm = new Immutable("I'm save here")
    imm.myProp = "nono doesnt work. and thats good" // error
    let mut: Mutable = imm  // you could also "hard" cast here: imm as unknown as Mutable
    mut.myProp = "there we go" // imm.myProp value is "there we go"
    

    Hope that helps.

提交回复
热议问题