What is the best way to convert a `readonly string[]` to a regular `string[]`?

My data setup is as follows (I am not declaring it as an enum because it is used in both TypeScript server code and non-TypeScript client code):

import { enumType } from 'nexus';

export const TYPE_ENUM = Object.freeze({
  H: 'H',
  S: 'S',
});
export const TYPES = Object.freeze(Object.values(TYPE_ENUM));

export const MyType = enumType({
  name: 'MyType',
  members: TYPES,
});

While working on this, TypeScript raised the following warning related to the members field:

Type '(readonly string[])[]' is not assignable to type '(string | EnumMemberInfo)[] | Record<string, string | number | boolean | object>'.
  Type '(readonly string[])[]' is not assignable to type '(string | EnumMemberInfo)[]'.
    Type 'readonly string[]' is not assignable to type 'string | EnumMemberInfo'.
      Type 'readonly string[]' is not assignable to type 'string'.ts(2322)
enumType.d.ts(29, 3): The expected type comes from property 'members' which is declared here on type 'EnumTypeConfig<"MyType">'

I understand the issue. It's not possible to insert a readonly string[] into something that expects a string[] due to their differences. My inquiry is about the best approach to resolve this.

I have noted that unwrapping and recreating the array seems to work: members: [...TYPES], but it doesn't feel quite right.

Answer №1

Upon closer inspection, you'll find the solution lies within the code snippet: members: [...TYPES]. This is necessary to provide an additional mutable Array for the enumType function.

While it may seem like there's an issue at first, rest assured that everything is as it should be. The reason for this is simple - the enumType function requires a mutable Array, allowing it to modify its contents. Take a look at this example:

function enumType(v: {name: string; members: string[]): string[] {
  v.members.push('JOKER');
  return v.members;
}

export const MyType = enumType({
  name: 'MyType',
  members: TYPES as unknown as string[],
});
// Expected result: MyType should be ['H', 'S', 'JOKER']. However, an error occurs in strict mode due to attempting to update a frozen array.

If you have control over the enumType function and know that it does not alter the array content, consider modifying it to accept a readonly string[]:

function enumType({v: {name: string; memebers: readonly string[]}) {
  ...
}

Alternatively, if you are unable to make changes to the function itself, using members: [...TYPES] remains the most effective approach.

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

What makes Mathematics a unique object in JavaScript programming?

Recently, I've dived into learning Javascript, so pardon me if my doubts seem a bit illogical. I came across the definition for a Math object, and here is the code snippet: interface Math { /** The mathematical constant e. This is Euler's nu ...

The NestJs project fails to display the updates when using the "tsc" command before running either "npm run start" or "npm run start:dev"

As a beginner in nestjs, I decided to start a tutorial to learn more about it. However, whenever I make updates or changes to my code, I don't see any changes reflected in the results. Can someone please assist me with this issue? Below are my tsconfi ...

React: Issue with passing arguments to redux action hooks

In my React application, I have implemented Redux-Toolkit to manage reducers and actions with slices. I am currently working on creating actions that can update and delete values from the store, requiring arguments for their usage. To achieve this, I have ...

The logic behind regular expressions

Currently working on building a web application with Angular 6 and I have a query: I'm in the process of developing a custom input component (specifically for text inputs) like so: @Component({ selector: 'input-text', templateUrl: &apos ...

Customizing TinyMCE's font style menu options

Our platform utilizes TinyMCE as in-place editors to allow users to make live edits to content. However, a challenge arises when using a dark background with light text, as TinyMCE defaults to using this text color rather than black. (Please note: the the ...

What is the most efficient way to retrieve and update a Stencil component parameter without triggering a rerender of the component?

Within my Stencil component, there exists a not-Prop member variable known as private _zIndex. The value of this variable can be adjusted via a method call like Method() setZIndex( zIndex : number );, or it may change internally during the component's ...

Arranging Select Dropdown Options in a Specific Order using Angular 7 and Typescript

My select dropdown is populated dynamically with options fetched from a service using *ngFor. I am looking to customize the order of these options. Can this be achieved through Angular code? The array structure is as follows: console.log(this.paymentTyp ...

Declaring properties for an interface

I've recently started using Typescript and I'm facing a problem with some interface props. There is an error message that says "Property 'services' does not exist on type 'IntrinsicAttributes & AkkordionProps[]", I'm confu ...

Displaying varying values of an object using TypeScript's console log trick

While using Angular version 8 with RJXS library, I encountered a peculiar issue when attempting to log an object variable: Object { carName: "Sorbonne", age: "20", type: "C1" } ​ carName: "BB" ​ age: "23&quo ...

Using template literals with Optional chaining in Javascript does not yield the expected results

Trying to implement template literal with optional chaining. type Item = { itemId:number, price: number}; type ItemType = { A:Item, B:Item }; const data : ItemType = { A:{itemId:1, price:2}, B:{itemId:2, price:3} }; let key = `data?.${variable}?.ite ...

Vuetify 3 does not display dialogs

I am attempting to integrate vuetify 3.alpha with vue 3. Below are the files I am working with: Temp.vue (obtained from vuetify example) <template> <div class="text-center"> <v-dialog v-model="dialog" w ...

In TypeScript, the function is failing to retrieve the complete array value

I'm facing an issue with a program that is supposed to piece together all the letters, but it's not functioning correctly. I've tried using the debugger, but it doesn't display any errors. Here's the code snippet: var phrase = [ &a ...

What is the best approach: Developing a class or a service to handle multiple interfaces?

My current project involves creating multiple interfaces, and I would like to keep them separate for clarity. Would it be wise to do this in a service or a class? Additionally, is it possible to utilize dependency injection for classes? Thank you for your ...

Leveraging symbols as object key type in TypeScript

I am attempting to create an object with a symbol as the key type, following MDN's guidance: A symbol value may be used as an identifier for object properties [...] However, when trying to use it as the key property type: type obj = { [key: s ...

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

In TypeScript, deduce the optional generic type automatically

Feeling a bit out of my depth here. I need to perform an inference on a generic that includes an optional "parse" function which returns the formatted value [or throws]. They say code speaks louder than words, so let's take a look at the example: exp ...

Utilize the reducer from another slice in Redux Toolkit

I am working with an authSlice const authSlice = createSlice({ name: 'authStore', initialState, reducers: { logout(state = initialState) { return { ...state, isAuthenticated: false }; }, }, extraReducers: (builder) => { ...

The type 'ReadableStream<any>' cannot be assigned to the parameter type 'ReadableStream'

Is there a way to convert a Blob into a Readable format? import {Readable} from 'stream'; const data: Blob = new Blob( ); const myReadable: Readable = (new Readable()).wrap(data.stream()); myReadable.pipe(ext); Encountering an error: ERROR in s ...

What are some ways to troubleshoot the TypeScript React demonstration application in Chrome?

Debugging a TypeScript app in the Chrome debugger is a straightforward process. First, you need to configure the tsconfig.json file: "sourceMap": true, Next, install ts-node and set a breakpoint in your TypeScript code using "debugger;" ...

Modify a particular attribute in an array of objects

I am currently working on an Angular project and dealing with the following array object: { "DATA": [ { "CUSTOM1": [ { "value": "Item1", ...