Creating a custom data type using values from a plain object: A step-by-step guide

I recently came across an object that looks like this:

const myObject = {
  0: 'FIRST',
  10: 'SECOND',
  20: 'THIRD',
}

My goal is to define a type using the values from this object, similar to this:

type AwesomeType = 'FIRST' | 'SECOND' | 'THIRD';

Any suggestions on how I can accomplish this?

Answer №1

If you want to determine the type of a variable (object), you can utilize the typeof operator. To avoid widening literal types, consider using the as const assertion:

const myObject = {
  0: 'FIRST',
  10: 'SECOND',
  20: 'THIRD',
} as const;

type Values<T> = T[keyof T];

type AwesomeType = Values<typeof myObject>; // "FIRST" | "SECOND" | "THIRD"

Try it out in the playground

Answer №2

Try doing it like this


type NewType = 'A' | 'B' | 'C';
type OurType = Record<number, NewType>

const ourObject: OurType = {
  0: 'A',
  10: 'B',
  20: 'C',
}


Check out this playground

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

Zod vow denial: ZodError consistently delivers an empty array

My goal is to validate data received from the backend following a specific TypeScript structure. export interface Booking { locationId: string; bookingId: number; spotId: string; from: string; to: string; status: "pending" | "con ...

Implementing an Ant Design Form field for an array of objects

Is it possible to edit an entity with a one-to-many relation? { id: 1, title: 'Title', tags: [ { id: 1 }, { id: 2 }, ], } Here is the code snippet: <Form.Item name={["tags", "id"]} > < ...

The pathway specified is untraceable by the gulp system

Hey there, I've encountered an issue with my project that uses gulp. The gulpfile.js suddenly stopped working without any changes made to it. The output I'm getting is: cmd.exe /c gulp --tasks-simple The system cannot find the path specified. ...

Show information retrieved from one API request within another API request

Currently, I am in the process of retrieving data from the Youtube API by utilizing 2 separate requests. One request is used to fetch a list of videos, while the other request provides details for each individual video. The initial request successfully di ...

tsconfig.json: No input files were detected in the configuration file

I am encountering an issue with my tsconfig.ts file where it says "No inputs were found in config file 'd:/self-study/Web/Learning/Express/tsconfig.json'. Specified 'include' paths were '["**/*"]' and 'exclude&a ...

Enforcing strict property validation on variables passed into TypeScript functions

Is there a method to enforce excess-property checking, not only for an inline object literal but also one derived from a variable? For instance, let's say I have an interface and a function interface Animal { speciesName: string legCount: nu ...

Guide to employing Axios types in project declaration files

When working on my project's type declaration file, I encountered a dilemma with using Axios types as part of my own types. The issue lies in the fact that all declarations for Axios are exported from their official repository. I specifically need to ...

Error: 'Target is not found' during React Joyride setup

I am attempting to utilize React Joyride on a webpage that includes a modal. The modal is supposed to appear during step 3, with step 4 displaying inside the modal. However, I am encountering an issue where I receive a warning message stating "Target not m ...

What could be causing the issue with dayjs dynamic importing in TypeScript?

Currently, I am developing a web screen within a .NET application and facing an issue with sending datetime preferences from the system to the web screen using CefSharp settings. AcceptLanguageList = CultureInfo.CurrentUICulture.Name In my TypeScript code ...

Exploring the implementation of query parameters in Nest.js

I am currently a freshman in the world of Nest.js. Below is an excerpt from my code: @Get('findByFilter/:params') async findByFilter(@Query() query): Promise<Article[]> { } I have utilized Postman to test this specific router. ht ...

After a loop, a TypeScript promise will be returned

I am facing a challenge in returning after all calls to an external service are completed. My current code processes through the for loop too quickly and returns prematurely. Using 'promise.all' is not an option here since I require values obtain ...

Typescript eliminates the need for unnecessary source code compilation

Within directory TS 2.6.2, there are three files: interface.ts: export interface Env { x: string } index.ts: import {Env} from './interface' // importing only the interface const env: Env = {x: '1'} console.log(env.x) tsconfi ...

Error encountered with TypeScript compiler when using a React Stateless Function component

I am attempting to create a React Stateless Function component using TypeScript. Take a look at the code snippet below: import * as React from 'react'; import {observer} from 'mobx-react'; export interface LinkProps { view: any; ...

What could be causing Angular to replace the original variable?

As a newcomer to Angular, I've been working on this code for hours now. Hopefully, it will all come together for someone out there who can make sense of it. export class QuizComponent implements OnInit { originalArray: IArray[] = []; tempArray: I ...

What is the best way to include a new attribute in a TypeScript internal object?

I am trying to include a property declaration in the window.history object, but I received a TypeScript error message This is my code: const historyInstance = createHashHistory(); // npm hoistory module window.history.historyInstance = historyInstance; / ...

Angular problem arises when attempting to map an array and selectively push objects into another array based on a specific condition

Setting up a cashier screen and needing an addToCart function seems pretty simple, right? However, I am encountering a strange logical error. When I click on an item to add it to the cart, my function checks if the item already exists in the array. If it d ...

Disabling the experimental app directory feature in NextJs

I've been working on a real-life project and decided to test out the new App directory feature that comes with Next.js version 13. However, I encountered some issues such as images and fonts not loading properly. Now, I'm looking to opt out of th ...

When utilizing the @Prop decorator in TypeScript, the compiler throws an error prompting the need to initialize the prop

Currently, I am utilizing Vue in combination with TypeScript along with the 'vue-property-decorator' package. When attempting to utilize a prop as shown below: @Prop({ default: '' }) private type: string An error is triggered by the ...

What is the best way to filter out specific data fields from console.log in JavaScript?

When working with Java, I often use lombok to exclude certain fields from being printed. For instance, the @ToString.Exclude annotation can be used to prevent printing the user token. import lombok.ToString; public class TokenResponse { @ToString.Excl ...

Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element. <ul> <li id="1" class="selectModal">First</li> <li id="2" class="selectModal">Seco ...