TypeScript - Readonly<T> 的可变性和反转

标签 typescript immutability

假设我有以下可变类:

class Foo {
    constructor(public bar: any) { }
}

我可以像这样定义这个类的 readonly 实例:
const foo: Readonly<Foo> = new Foo(123);
foo.bar = 456; // error, can't reassign to bar because it's readonly.

我希望能够做的是与此相反的类,其中类是不可变的:
class Foo {
    constructor(public readonly bar: any) { }
}

然后能够像这样制作可变版本:
const foo: Mutable<Foo> = new Foo(123);
foo.bar = 456;

这可能吗?

最佳答案

是的,您可以在类型定义中使用 -readonly

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

const foo: Mutable<Foo> = new Foo(123);
foo.bar = 456;

Playground

但请记住它只是类型定义,它不会改变原始逻辑。

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

class Foo {
    get test(): boolean {
      return true;
    }

    constructor(public readonly bar: any) { }
}

const foo: Mutable<Foo> = new Foo(123);
foo.bar = 456;
foo.test = false; // oops, it will cause an error.

关于TypeScript - Readonly<T> 的可变性和反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62038161/

相关文章:

javascript - 在javascript中创建不可变对象(immutable对象)

浏览器中的 Typescript 转译与预编译 js 文件

angular - 如何在 Angular 4 Material 排序中对日期/时间列进行排序?

c# - 如果安全不是问题,那么不可变接口(interface)是一个好的模式吗?

arrays - 如何快速卡住数组?

boolean - 如果 boolean 值在 Java 中是不可变的,我如何才能改变这个 boolean 值?

javascript - 我什么时候应该使用 icepick.merge 而不是 lodash.merge

angular - 如何从 Angular 中的另一个组件调用方法?

javascript - 通过代码更改 Angular 垫选择占位符颜色

javascript - 如何使用 Rollup 将本地 typescript 文件捆绑到主包中