Getting the readonly-item type from an array in TypeScript: A step-by-step guide

Is it possible to create a readonly item array from a constant array?

const const basicValueTypes = [{
  value: 'number',
  label: 'Number'
},{
  value: 'boolean',
  label: 'Boolean'
}];

type ReadonlyItemArray = ???

type ReadOnlyBasicValueTypes = ReadonlyItemArray<typeof basicValueTyeps>;
/*
↓↓↓↓
ReadOnlyBasicValueTypes = (
  {value: 'number', label: 'Number'}
| {value: 'boolean', label: 'Boolean'}
)
*/

Update: I discovered that I can make each item as const:

const basicValueTypes = [{
  value: 'number',
  label: 'Number'
} as const,{
  value: 'boolean',
  label: 'Boolean'
} as const];

type BasicValueTypes = typeof basicValueTypes[number]['value'];
// BasicValueTypes = "number" | "boolean"

However, I am still interested in knowing if the creation of the aforementioned ReadonlyItemArray type is feasible?

Answer №1

If you want to make the basicValueTypes variable immutable (readonly), simply use as const.


const basicValueTypes = [{
    value: 'number',
    label: 'Number'
}, {
    value: 'boolean',
    label: 'Boolean'
}] as const;

To determine the type, you can utilize the typeof keyword:

type Immutable = typeof basicValueTypes

For creating a literal type, follow this syntax:

type Literal = [number, string]

In addition, there is a built-in readonly array feature:

type Arr = ReadonlyArray<string>

const arr:Arr=['a','b']
arr.push('c') // error

However, attempting something like this will not work:

const ReadOnlyBasicValueTypes = ReadonlyItemArray<typeof basicValueTyeps>;

This is because types are not constructors in TypeScript like they are in F# - they are only used for typing purposes. The TypeScript compiler removes them from the source code, resulting in pure JavaScript output.

Update

 const basicValueTypes = [{
  value: 'number',
  label: 'Number'
},{
  value: 'boolean',
  label: 'Boolean'
}] as const;

type Basic = typeof basicValueTypes;
type Item = Basic[number] // check this type

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

Angular Inner Class

As a newcomer to Angular, I have a question about creating nested classes in Angular similar to the .NET class structure. public class BaseResponse<T> { public T Data { get; set; } public int StatusCo ...

The error message "Property 'showUserDropdown' is not found on type '{}'.ts" indicates that the specified property is not present in the defined

While creating a basic Vue component, I encountered an error in the IDE regarding the {{ showUserDropdown }} with the message: Property 'showUserDropdown' does not exist on type '{}'.ts Despite adding it to data, <template> &l ...

Experiencing the 'invalid_form_data' error while attempting to upload a file to the Slack API via the files.upload method in Angular 8

I am currently working on a project that involves collecting form data, including a file upload. I am trying to implement a feature where the uploaded file is automatically sent to a Slack channel upon submission of the form. Despite following the guidance ...

Issues with React Material UI Select functionality not performing as expected

I've been working on populating a Select Component from the Material UI library in React, but I'm facing an issue where I can't choose any of the options once they are populated. Below is my code snippet: import React, { useState, useEffect ...

Tips for using Firebase Parameterized configuration with Typescript when setting the region() on a Firebase Function

Based on this documentation, I am attempting to utilize a Firebase Parameterized configuration directly within the region() config for a function. My .env file looks like this: LOCATION = 'australia-southeast1'; And my config file is structured ...

What is the best way to showcase several images using Sweet Alert 2?

In the process of developing my Angular 2 application, I have incorporated sweet alert 2 into certain sections. I am looking to showcase multiple images (a minimum of two) at the same time in the pop-up. Does anyone have any suggestions on how to achieve ...

Downloading fonts from Google Fonts is always a struggle when using Next.js

After initializing a fresh Next.js project using create-next-app, I managed to successfully launch it with npm run dev. However, an issue arises every time Next.js boots up, displaying the following error: FetchError: request to https://fonts.gstatic.com/ ...

What is the correct method for typing sagas?

After diligently following the official redux documentation for integrating with TypeScript, which can be found at https://redux.js.org/recipes/usage-with-typescript, I successfully typed actions, reducers, react components, and more. However, my progress ...

Error: Trying to modify a property that is set as read-only while attempting to override the toString() function

I have a specific object that includes an instance variable holding a collection of other objects. Right now, my goal is to enhance this list of elements by adding a customized toString() method (which each Element already possesses). I experimented with t ...

What is the best way to insert information into my SQLite database?

Hey there! I'm new to programming and recently started working on an IONIC App. However, I've hit a roadblock. My goal is to create a phone book feature where users can get random JSON contacts and save them to their sqlite database. Here's ...

Displaying sorted objects from Angular serviceIn Angular 8, let's retrieve an object

In my Angular8 application, I am running a query that fetches a data object. My goal is to sort this data object based on the order value and then display each product item on the browser. For example, here is an example of how the output should look like ...

Preventing the display of the login page for an authenticated user in Angular

My application has different modules for authentication, dashboard, and root routing. The auth module contains routes for sign-in, the dashboard module has routes for home with authentication guard, and the root module redirects to home or a PageNotFound c ...

Step-by-step guide on crafting a harmonious row of a label and a responsive button group

One of my projects involves a form that contains a list of elements. I want this form to be responsive and suitable for all screen sizes. When I initially run the project on a larger screen, everything looks good. However, when I resize the screen to a sma ...

Retrieve a specific attribute from a collection of JSON objects and transfer it to a separate object

Having a JSON object array with various project information: [ {"Project":"Project 1","Domain":"Domain1","Manager":"Manager1"}, {"Project":"Project 2","Domain":&q ...

Splitting Angular modules into separate projects with identical configurations

My Angular project currently consists of approximately 20 different modules. Whenever there is a code change in one module, the entire project needs to be deployed. I am considering breaking down my modules into separate projects for individual deployment. ...

How can I modify the pristine state of NgModel in Angular 2 using code?

Whenever you update the NgModel field, it will automatically set model.pristine to true. Submitting the form does not change the "pristine" status, which is expected behavior and not a bug. In my situation, I need to display validation errors when the fo ...

Formik's handleChange function is causing an error stating "TypeError: null is not an object (evaluating '_a.type')" specifically when used in conjunction with the onChange event in DateInput

When using the handleChange function from Formik with the DateInput component in "semantic-ui-calendar-react", I encountered an error upon selecting a date. https://i.stack.imgur.com/l56hP.jpg shows the console output related to the error. AddWishlistFor ...

Discovering the Java Map's value in Typescript

My application's backend is built using Spring Boot and the frontend is Angular 7. I need to send a map as a response, like this: Map<String, Object> additionalResponse = new HashMap<>() { { put("key1"," ...

Challenge Encountered with Create-React-App TypeScript Template: Generating JS Files Instead of TSX Files

Encountering a problem setting up a new React application with TypeScript using the Create-React-App template. Followed the guidelines on the official documentation (https://create-react-app.dev/docs/adding-typescript/) and ran the command below: npx creat ...

React-query: When looping through useMutation, only the data from the last request can be accessed

Iterating over an array and applying a mutation to each element array?.forEach((item, index) => { mutate( { ...item }, { onSuccess: ({ id }) => { console.log(id) }, } ); }); The n ...