How can you prevent the keys from being read-only when mapping onto a type?

Here's a common query: How can I change keys from readonly to writable when using a type that is Readonly?

For example:

type Foo = Readonly<{
  foo: number
  bar: number
}>

type Bar = /* What's the method to duplicate the Foo type, but with writable keys? */

Answer №1

If you want to remove readonly when mapping, try using the -readonly attribute.

export type Foo = Readonly<{
  foo: number
  bar: number
}>;

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

export type Bar = Writeable<Foo>;
let x:Bar = {
  foo: 123,
  bar: 456
}
x.bar = 123; // This is allowed 

🌹

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updates made in the type declaration files are not being displayed

I'm currently working on an express app and I have been trying to add a new property to the Request's class instance. To achieve this, I created a type.d.ts file at the root of my project that looks like this: type User = { name: string } de ...

How can I use Angular2 to draw a square [input] number of times?

I need to create a specific number of squares within a container using Angular2. Can you please provide me with a straightforward example, preferably utilizing canvas? Currently, I have converted webpack starter for use with Angular: This is the code ins ...

Is it possible for VSCode to automatically generate callback method scaffolding for TypeScript?

When working in VS + C#, typing += to an event automatically generates the event handler method scaffolding with the correct argument/return types. In TypeScript, is it possible for VS Code to offer similar functionality? For instance, take a look at the ...

What advantages does using an RxJS Subject have over handling multiple event listeners individually in terms of speed

After investigating a page's slow performance, I identified an angular directive as the root cause. The culprit was a piece of code that registered event listeners on the window keydown event multiple times: @HostListener('window:keydown', ...

What is the most effective method for delivering a Promise after an asynchronous request?

Currently, I am working on creating an asynchronous function in TypeScript that utilizes axios to make an HTTP request and then returns a Promise for the requested data. export async function loadSingleArweaveAbstraction(absId : string) : Promise<Abstra ...

Need at least one of two methods, or both, in an abstract class

Consider the following scenario: export abstract class AbstractButton { // Must always provide this method abstract someRequiredMethod(): void; // The successor must implement one of these (or both) abstract setInnerText?(): void; abst ...

What does the concept of "signaling intent" truly signify in relation to TypeScript's read-only properties?

Currently diving into the chapter on objects in the TypeScript Handbook. The handbook highlights the significance of managing expectations when using the readonly properties. Here's a key excerpt: It’s crucial to clarify what readonly truly signif ...

Troubleshooting CORS errors in axios requests within a Next.js application

Encountering an issue while attempting to make an axios call to my API on a different localhost. How can this be resolved? The tech stack being used includes Next.js, TypeScript, and Axios. Below is the function which - although written poorly for testing ...

Is it possible to maintain the input and output types while creating a function chain factory in

Take a look at the following code snippet involving pyramids: /** * @template T, U * @param {T} data * @param {(data: T) => Promise<U>} fn */ function makeNexter(data, fn) { return { data, next: async () => fn(data), }; } retu ...

Implementing computed properties: A guide to incorporating type setting

I currently have two separate interfaces defined for Person and Dog. interface Person { name: string; weight: number; } interface Dog { name: string; mass: number } const specificAttribute = isDog ? 'mass' : 'weight'; ...

Guide to defining a typescript class property using an index signature

type TField = { field1: string; field2: boolean; field3: TMyCustom; } class Test1 { // I opt for using TypeScript's index signature to declare class fields [key: keyof TField]: TField[typeof key] // Instead of individually declaring each ...

What is the best way to combine properties from Type1 and Type2 to create a new type in Typescript?

Here is a snippet of code I'm working with: interface Notification { message: TemplatedEmail & Email, //current attempt which doesnt do what I want } interface Destination { ccAddresses?: string[], bccAddresses?: string[], toAddresses: st ...

Updating the DOM with an EventListener in Angular 5 is not functioning properly

Situation : Utilizing an Angular PWA for communication with an iOS native app via WKWebview. Implementing messageHandlers to facilitate data sharing between TypeScript and Swift logic code. Issue : Employing addEventListener to monitor a specific event on ...

Is there a specific type of function missing in Typescript?

I am facing a challenge in converting an existing JavaScript code to Typescript. The original javascript code is as follows: object.getsomething( function(err, result) { // async }); I am confused about how to properly type the parameter "function(er ...

Issue TS2322: The type 'Observable<any>' cannot be matched with type 'NgIterable<any> | null | undefined'

Encountering an error while attempting to fetch data from the API. See the error image here. export class UserService { baseurl: string = "https://jsonplaceholder.typicode.com/"; constructor(private http: HttpClient) { } listUsers(){ //this ...

Gathering adorned categorizations (sans any listed category divisions)

My current setup involves an event dispatcher class that triggers listeners on specified occurrences. I've successfully implemented registering event listeners via decorators, but I feel like there may be a better solution out there. At the moment, e ...

Enclose the type definition for a function from a third-party library

I prefer to utilize Typescript for ensuring immutability in my code. Unfortunately, many libraries do not type their exported function parameters as Readonly or DeepReadonly, even if they are not meant to be mutated. This commonly causes issues because a ...

Adding a custom type to a selected option for the onChange event in React-Select can be done by modifying the

After creating a SelectBox component using react-select and applying onChange event to it, I encountered an issue. I wanted to include a type "SelectedItemType" to the selected option in the onChange event, but the property of onChange was defined as (prop ...

Is ngOnDestroy executed within Angular services?

Is there a way to confirm if the ngOnDestroy method in my UserServiceService class is functioning properly? I want this service to continue running until the project starts and ends, with ngondestroy method executing once the application (website) is clo ...

I seem to be missing some properties in the request body schema. Why am I receiving an incomplete model for

Seeking assistance in grasping the working of models in loopback4. Here's a model I defined: @model() export class ProductViewConfig extends BaseConfig { @property({ type: 'string', id: true, generated: true, }) _id?: strin ...