In TypeScript, is it possible to remove the readonly modifier from a type?
For example:
type Writeable<T> = { [P in keyof T]: T[P] };
Usage:
interface Foo { readonly bar: boolean; } let baz: Writeable<Foo>; baz.bar = true;
Is it possible to add a modifier to the type to make all the properties writeable?
TypeScript includes the readonly keyword that makes a property as read-only in the class, type or interface. Prefix readonly is used to make a property as read-only. Read-only members can be accessed outside the class, but their value cannot be changed.
Sample Code: class C { readonly readOnlyProperty: string; constructor(raw: string) { this. process(raw); } process(raw: string) { this. readOnlyProperty = raw; // [ts] Cannot assign to 'readOnlyProperty' because it is a constant or a read-only property. } }
C# Readonly Keyword Syntax Following is the syntax of defining read-only fields using readonly keyword in c# programming language. readonly data_type field_name = "value"; If you observe the above syntax, we used a readonly keyword to declare a read-only variable in our application.
There's a way:
type Writeable<T extends { [x: string]: any }, K extends string> = { [P in K]: T[P]; }
(code in playground)
But you can go the opposite way and it will make things much easier:
interface Foo { bar: boolean; } type ReadonlyFoo = Readonly<Foo>; let baz: Foo; baz.bar = true; // fine (baz as ReadonlyFoo).bar = true; // error
(code in playground)
Since typescript 2.8 there's a new way to do it:
type Writeable<T> = { -readonly [P in keyof T]: T[P] };
If you need your type to be writeable recursively, then:
type DeepWriteable<T> = { -readonly [P in keyof T]: DeepWriteable<T[P]> };
These type
definitions are called mapped types
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With