Ways to obtain a data type as an element in an array?

const ratingList = {1: "", 2: "", 3: "", 4: "", 5: ""}
  
type ratingType = keyof typeof ratingList

......

{Object.keys(ratingList).map((value, index) => {
   if (parseInt(value) <= rating)
       return <div key={index}><TiStar size={22} /></div>
   else
       return <div key={index}><TiStarOutline size={20} /></div>
 })}

I am seeking a way to create a type that corresponds to the elements in the rating list. Essentially, I want the ratingList array [1, 2, 3, 4, 5] to be easily accessible for use elsewhere. The type should specifically represent each element of that array. Any suggestions on how to manage and update the rating list more efficiently are greatly appreciated!

Answer №1

If I have correctly grasped your query, there is a solution to achieve what you desire:

const ratingList = [1, 2, 3] as const 
// This can also be applied with string values such as ["a", "b"] as const

type RatingListMember = typeof ratingList[number] // Resulting in type : 1 | 2 | 3
// When using strings it would result in type : "a" | "b"

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 is the best way to determine if an array of objects is present in the state of a React

Currently, I am in the process of developing a dynamic form using React JS. One aspect of my form involves an input field with a limit of 10 characters. To enhance the cleanliness of my code, I have constructed an object and utilized mapping to streamline ...

Issue: Headers cannot be modified after being sent to the client - Node.js with Express and TypeScript

Greetings. I'm encountering the "Cannot set headers after they are sent to the client" error when trying to use res.redirect. This specific section of the code is triggered by a verification email. Everything works smoothly until the redirect step, w ...

Return true for cucumber datatable in typescript without fail

I am facing an issue where the following step definition always returns true even for incorrect data from the dataTable. Can someone assist me in correcting the syntax in TypeScript with Chai assertions? Then(/^Verify the following details in report$/, a ...

NextJS encounters a TypeError while using ChartJS due to its inability to read properties of null, specifically 'useRef'

Recently, I've been working on incorporating graphs using ChartJS into my NextJS application. However, I've encountered some difficulties with rendering them. Despite following several tutorials and articles, I keep encountering the same error. ...

Exploring Angular 2/4: Unpacking the Process of Accessing API Data Using Tokens

Hello there, I am trying to retrieve API data with a token using Angular 2/4. Below is the code I have written: import { Component, ViewEncapsulation } from '@angular/core'; import { Http, Response } from '@angular/http'; import &apos ...

The server side is encountering difficulty in reading the payload of the requestResponse call

Look at this TS client code snippet below : this.socketClient.connect().subscribe({ onComplete: socket => { const endpoint = ‚endpoint’; socket.requestResponse({ data: id, //id is a non-empty string metadata ...

Troubleshooting TypeScript when importing external JavaScript: Module not found or no type declaration file available

I recently acquired a VueJS admin template built in JS and am looking to integrate it into my existing TS application. However, when I attempt to transfer the components, views, and other elements, I encounter the following error message. Is there a way to ...

Is there a method for establishing a connection to oracledb using TypeScript ES6 class and module?

My goal is to implement an Oracle connection using Typescript ES6 Class module. I have successfully installed the @types/oracledb package and oracledb package, with the Jasmin framework used in my project. Below is the code I have implemented: import * ...

What steps should I take to enable users of my library to customize component templates as needed?

I created a customized component to enhance the appearance of bootstrap form controls, intended for use in various projects. I am considering transforming this into a library (a separate npm package with its own @NgModule), but some projects may wish to mo ...

Working with nested arrays in TypeScript and how to push values onto them

I am facing some challenges with nested array behavior in TypeScript. I am looking for a way to define a single type that can handle arrays of unknown depth. Let me illustrate my issue: type PossiblyNested = Array<number> | Array<Array<number& ...

Type of JavaScript map object

While exploring TypeScript Corday, I came across the following declaration: books : { [isbn:string]:Book}={}; My interpretation is that this could be defining a map (or dictionary) data type that stores key-value pairs of an ISBN number and its correspon ...

What are the steps to incorporate dynamic routing within Next.js?

After converting my React.js app to Next.js, I am now looking to implement routing to my blog details page upon clicking a card on the blog page. The data is being fetched from a Heroku API. In React, I used react-router-dom for this purpose. Can anyone ...

ZOD distinguishes between unions based on two discriminator fields

I need to differentiate between two fields in a schema: enum Action = { CREATE: 'create' } enum ObjectType = { Potatoe: 'potatoe', Tomatoe: 'tomatoe' } export const TestSchema = z.object({ action: z.nativeEnum( ...

Ways to include various inputs with chip

I am currently working on a project that involves implementing an email field using the chip component. However, I have encountered an issue where pasting multiple email values for the first time inserts them into the field successfully. But when I try to ...

Unable to globally override the default font in MUI theme

Objective: My goal is to customize the default font in MUI themes. Issue: Despite reviewing MUI documentation and conducting research on Stack Overflow, I am facing difficulty overriding a custom font globally across my theme. Theme setup: import { creat ...

Ways to properly assign a key in a Generic Interface as the interface key

Can someone assist me with TypeScript generics? I am wondering how to access the T["value"] field within the ActionAdd interface. type UserValue = { username: string; }; interface User { id: number; value: UserValue; } interface ActionAdd<T = unkn ...

Manipulate and send back information from Observable in Angular

Here is an example of a scenario where I have created a service to retrieve a list of properties. Within this service, I am utilizing the map function to manipulate the response and then returning the final array as an Observable. My question is: How can ...

Unable to attach API data to client variable in Angular 6

I am encountering a challenge with binding requested API data to a variable in my component. Firstly, here is my server-side method (using Express and Mongoose). app.post('/api/rolloutMeeting', async (req, res)=> { var singleMeetingI ...

Is it possible to create a NextJS API route without including the "api" in the URL?

In the latest version of NextJS, version 13, I have set up an API route. You can access this endpoint at http://localhost:8080/api/foo/bar // pages/api/foo/bar.ts import { NextApiRequest, NextApiResponse } from "next"; export default async func ...

The absence of a function implementation right after the declaration within a TypeScript class is a common issue that needs

I received a handwritten array to populate a table for my class, however I am now fetching this array's content from a JSON during the ngOnInit phase and it is not structured in the way I require. Therefore, I am attempting to create a function that ...