Guidance on specifying a type based on an enum in Javascript

I have a list of animals in an enum that I want to use to declare specific types. For instance:

enum Animals {
  CAT = 'cat',
  DOG = 'dog',
}

Based on this Animal enum, I wish to declare a type structure like so:

type AnimalType = {
  cat_price: string,
  cat_from: string,
  cat_color: string,
  dog_price: string,
  dog_from: string,
  dog_color: string,
}

Is there a way to dynamically update the AnimalType whenever the values in the Animals enum change? Any insights or suggestions would be greatly appreciated.

Answer №1

Interestingly, TypeScript makes this achievable through the use of template literal types and key remapping:

enum Animals {
  CAT = 'cat',
  DOG = 'dog',
}

type AnimalData = {
  price: number,
  from: string,
  color: string,
}

type MyType = {
  [Key in keyof AnimalData as `${Animals}_${Key}`]: AnimalData[Key]
}

const foo: MyType = {
  cat_price: 42,
  cat_from: 'Africa',
  cat_color: 'teal',
  dog_price: '37',  // Error! Type 'string' is not assignable to type 'number'.
  dog_from: 'Mexico',
  dog_colr: 'blue', // Error! Object literal may only specify known
                    // properties, but 'dog_colr' does not exist in type
                    // 'MyType'. Did you mean to write 'dog_color'?
}

Playground link

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

Discovering the title of a page in layout using Nextjs 13

How do I extract the title stored in the metadata object within the layout.tsx file? page.tsx: import { Metadata } from 'next'; export const metadata: Metadata = { title: 'Next.js', }; export default function Page() { return &a ...

Making a synchronous call to a web API using JQuery

Understanding JQuery promises and deferred objects has been a bit of a challenge for me, so please bear with me. I should also mention that my application is built using React, Typescript, and ES6. Let's imagine we have an array of objects: [{ Objec ...

Tips on setting a singular optional parameter value while invoking a function

Here is a sample function definition: function myFunc( id: string, optionalParamOne?: number, optionalParamTwo?: string ) { console.log(optionalParamTwo); } If I want to call this function and only provide the id and optionalParamTwo, without need ...

I'm curious, which ref tag should I utilize for draft.js?

I'm currently working on a form using Draft.js with Next.js and TS, but I've encountered some errors in my code. Here is what I have so far: import {Editor, EditorState} from 'draft-js'; const [editorState, setEditorState] = useState( ...

Can Typescript restrict a value to only exist within a specified set of key names within the same object?

I am completely new to Typescript and I am fascinated by the way it can check types. One thing I would like to know is if Typescript can be used to verify at compile time whether a value's domain falls within a predefined set of key names that are de ...

Enhance the navigation scroll bar with a blur effect

I'm looking to create a navigation bar with a cool blur effect as you scroll. Everything seems to be working fine, except when I refresh the page the scrollbar position remains the same and window.pageYOffset doesn't give me the desired result. T ...

Using TypeScript, a parameter is required only if another parameter is passed, and this rule applies multiple

I'm working on a concept of a distributed union type where passing one key makes other keys required. interface BaseArgs { title: string } interface FuncPagerArgs { enablePager: true limit: number count: number } type FuncArgs = (Fu ...

Encountering ExpressionChangedAfterItHasBeenCheckedError during ngOnInit when utilizing Promise

I have a simple goal that I am working on: I want to display data obtained from a service in my component. This is how it used to work: In my component: ... dataSet: String[]; ngOnInit(){ this._service.getDataId().then(data => this.dataSet = da ...

Conceal a table if it has no content

I am dealing with 2 tables that contain various data sets. img01 If both of my tables happen to be empty, I would prefer them to be hidden. img02 Is it feasible to implement this in Angular? If you have a solution for me, I would be eager to give it a ...

You can only use a parameter initializer within the implementation of a function or constructor

I recently started learning TypeScript and am currently using it for React Bricks. I've been working on rendering a 3D object with three.js, but I keep encountering the error mentioned above. I've attempted various solutions such as passing color ...

The issue with Angular 4 imports not refreshing in a .less file persists

Currently, I am in the process of developing a small Angular project that utilizes less for styling purposes. My intention is to separate the styling into distinct folders apart from the components and instead have a main import file - main.less. This fil ...

Why do variables in an HTML file fail to update after being navigated within onAuthStateChanged?

Currently, I am working with Ionic 5 and Firebase. Everything is running smoothly until I implemented the onAuthStateChanged function to persist login for authenticated users. Here is the code snippet: this.ngFireAuth.onAuthStateChanged((user) => { ...

Disseminate several outcomes using a Discord bot

My first experience using stackoverflow was to seek help regarding a bot created to post results whenever a new episode of a show in the search list is added on nyaa.si. The issue I'm facing is that the bot posts the same episode multiple times within ...

I am unable to locate the type definition file for 'core-js' at the moment

Currently, I am in the process of developing an application using angular2 along with angular-cli. Surprisingly, angular-in-memory-web-api was not included by default. In order to rectify this, I took the initiative to search for it and manually added the ...

Base class template parameter as internal enum

pragma once #include "stdafx.h" #include "Token.h" //Enum inside class Number enum class NumberEnum {ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE}; class Number : public Token<NumberEnum> { private: public: ...

Using TypeScript to destructure by providing types

I encountered an issue while trying to destructure some code. The error message Property 'name' does not exist on type '{}'. is appearing. I thought about using let user:any = {}; as a workaround, but that goes against the eslint rule o ...

Describe the TypeScript type for an object with constant keys

My query resembles the one found in this Typescript interface definition question, but has a slight variation. I am beginning with an object where the keys are constants: const KEYS = { KEY1: 'hello', KEY2: 'world' } as const; How ...

Angular 6 ActivatedRoute Parameters

I'm having trouble retrieving the data of each record using ActivatedRoute. I've been able to get the ID for each one, but I can't seem to access the other data. Any suggestions? Check out my stackblitz example: https://stackblitz.com/edit/ ...

The React Quill interface is unable to load due to an undefined window

I recently integrated React Quill into my Next.js project and everything was functioning properly. However, I encountered an issue when attempting to incorporate ImageResize into the editor. Upon adding the line Quill.register('modules/imageResize&ap ...

What is the best way to revert a screen's state back to its original state while utilizing react navigation?

How can I reset the state in a functional component back to its initial state when navigating using navigation.navigate()? For example, if a user navigates to screen A, sets some state, then clicks a button and navigates to screen B, and then goes back to ...