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

7

假设我有以下可变类:

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;

可以的吗?

1
你可以将Foo转换为Mutable<Foo>,但不建议这样做,因为它是你的Foo类的契约... 你为什么想这样做呢? - HTN
@htn 因为我认为可变性应该是选择加入,而不是选择退出。如果假设 Mutable<T> 是像 Readonly<T> 这样的类型,那么我该如何转换为 Mutable<Foo> - Matthew Layton
1
你可以定义Mutable,例如:type Mutable<T> = { -readonly [P in keyof T]: T[P] };。然而,这是危险的,因为你可能会在以后更改类Foo的实现,认为bar是只读的==>它可能会破坏你的应用程序。 - HTN
1个回答

7

是的,你可以在类型定义中使用-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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接