Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - removing readonly modifier

Tags:

typescript

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?

like image 346
MichaelAttard Avatar asked Mar 24 '17 12:03

MichaelAttard


People also ask

Is readonly TypeScript?

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.

How do you assign values to readonly property in TypeScript?

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. } }

What is the syntax for making a property read-only?

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.


1 Answers

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)


Update

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

like image 128
Nitzan Tomer Avatar answered Sep 17 '22 09:09

Nitzan Tomer