How can I change a readonly property in TypeScript?

后端 未结 6 1915
眼角桃花
眼角桃花 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:20

    My current solution for TypeScript 3.6.3

    type Mutable = {
       -readonly [k in keyof T]: T[k];
    };
    
    class Item {
      readonly id: string;
    
      changeId(newId: string) {
        const mutableThis = this as Mutable;
        mutableThis.id = newId;
      }
    }
    

提交回复
热议问题