TypeScript - 删除只读修饰符

问题描述 投票:0回答:2

在 TypeScript 中,是否可以从类型中删除 readonly 修饰符?

例如:

type Writeable<T> = { [P in keyof T]: T[P] };

用途:

interface Foo {
    readonly bar: boolean;
}

let baz: Writeable<Foo>;

baz.bar = true;

是否可以向类型添加修饰符以使所有属性都可写?

typescript
2个回答
178
投票

有一个办法:

type Writeable<T extends { [x: string]: any }, K extends string> = {
    [P in K]: T[P];
}

操场上的代码

但是你可以采取相反的方式,这会让事情变得更容易:

interface Foo {
    bar: boolean;
}

type ReadonlyFoo = Readonly<Foo>;

let baz: Foo;
baz.bar = true; // fine

(baz as ReadonlyFoo).bar = true; // error

操场上的代码


更新

从 typescript 2.8 开始,有一种新的方法可以做到这一点:

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

如果您需要您的类型可递归写入,那么:

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

这些

type
定义称为 映射类型


0
投票

要添加到接受的答案,如果您只想从类型中删除一个或少量只读道具,您可以这样做(playground):

interface Foo {
    readonly bar: boolean;
}
type WriteableFoo = Foo & { bar: Foo['bar'] };
const baz: Foo = { bar: true };
// baz.bar = true; // Cannot assign to 'bar' because it is a read-only property.(2540)
(baz as WriteableFoo).bar = false;

适用于 v4 和 5,但奇怪的是,不适用于 v3(可能更早)。

© www.soinside.com 2019 - 2024. All rights reserved.