A versatile union type in Typescript that combines dynamic properties of dynamic objects

Is there a way to create a unified union type based on the dynamic properties of an object?

const config = {
  devices: {
    Brand1: ['model1'],
    Brand2: ['model2', 'model3'],
  },
};

export type DeviceBrand = keyof typeof config.devices; // 'Brand1' | 'Brand2'

export type DeviceModel = ___________; // 'model1' | 'model2' | 'model3'

How can I transform DeviceModel into a union type that includes all models from the brands in the object?

Answer №1

Here is the solution:

const deviceConfig = {
  devices: {
    Brand1: ['model1'],
    Brand2: ['model2', 'model3'],
  },
} as const;

export type DeviceBrand = keyof typeof deviceConfig.devices; // 'Brand1' | 'Brand2'

export type DeviceModel = typeof deviceConfig['devices'][DeviceBrand][number]; // 'model1' | 'model2' | 'model3'

const a: DeviceModel = 'model1' // valid
const b: DeviceModel = 'model4' // type error

Make sure to utilize the const assertion for the deviceConfig variable to narrow down the type to specific string values

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

How should we correctly import jquery.inputmask?

Struggling to import jquery.inputmask using webpack and TypeScript? Head over to this discussion at Issue #1115 : Here's how I configured things with jqlite: To import in your app, use the following code: import InputMask from 'inputmask&apos ...

Adjust the color of the icon depending on the value

I am new to Angular2 and I'm looking for a way to dynamically change the CSS of an icon based on specific values. Here is the code in HTML: <li><i class="fa fa-check" [style.color]="'switch(types)'"></i>{{ types }}</l ...

Angular2 - leveraging root-relative imports

Having trouble with imports in angular2/typescript? Want to use paths relative to the project root like 'app/components/calendar', but currently stuck using something like this: //app/views/order/order-view.ts import {Calendar} from '../../ ...

React Query successfully retrieves the path, but unfortunately fails to render the image in the display

Currently facing an issue where I am trying to retrieve images from the backend using ReactQuery. Here is the ReactQuery code snippet: export const useGetProductImagesByProductId = (productId: string) => useQuery({ queryKey: ['productIm ...

Is it possible to preserve the numerical type of a percentage when applying number formatting?

After applying number formatting, I converted a numerical value of 150 to 150.00%. Although this is the desired display format with the percentage sign included, the data type remains as string instead of number. Is there a method to convert it back to a ...

When the boolean in RxJS skipWhile remains true

My current scenario involves a specific use-case: There is a service that queues calculation tasks assigned with a certain ID. I have set up an observable to monitor the status of the service. When the ID is still in the queue, the query result is true (i ...

Tips for expanding the functionality of the d3-selection module using TypeScript

I am currently working on a project that involves TypeScript and d3. I have already installed 'd3' and '@types/d3', and my use of d3 looks like this: import * as d3 from 'd3'; const x = d3.scaleLinear ... Everything was goin ...

Having trouble changing the query string in the URL with Angular 4?

My search form includes various filters such as text inputs, checkboxes, and radio buttons. Whenever the user interacts with these filters, the query string in the URL needs to be updated. Consider the following scenario: http://example.com/search?myFilt ...

Arranging a list of objects with a designated starting value to remain at the forefront

Consider the array and variable shown below: array = ['complete','in_progress','planned']; value = 'planned'; The goal is to always sort the array starting with the 'value' variable, resulting in: array ...

Create a function that retrieves the value associated with a specific path within an object

I want to implement a basic utility function that can extract a specific path from an object like the following: interface Human { address: { city: { name: string; } } } const human: Human = { address: { city: { name: "Town"}}}; getIn< ...

Is it possible to use non-numeric values as keys in a Typescript Map?

During a lesson: private items: Map<number, string> = new Map(); ... this.items[aNumber] = "hello"; Results in this error message: An element has an any type because the expression of type number cannot be used to index type Map<numbe ...

The absence of defined exports in TypeScript has presented a challenge, despite attempting various improvement methods

I've exhausted all available resources on the web regarding the TypeScript export issues, but none seem to resolve the problem. Watching a tutorial on YouTube, the presenter faced no such obstacles as I am encountering now. After updating the tsconf ...

Retrieving the value of a selected option in Angular

I have the following dropdown select in my HTML and I am currently retrieving the text content of the selected option. How can I access the value attribute instead? Here is the dropdown select: <form [formGroup]="angForm" class="form-inline my-5 my-l ...

Concealing the sidebar in React with the help of Ant Design

I want to create a sidebar that can be hidden by clicking an icon in the navigation bar without using classes. Although I may be approaching this incorrectly, I prefer to keep it simple. The error message I encountered is: (property) collapsed: boolean ...

Utilizing shared components across a Next.js application within a monorepo

Utilizing a monorepo to share types, DTOs, and other isomorphic app components from backend services (Nest.js) within the same mono repo has presented some challenges for me. In my setup, both the next.js app and nest.js app (which itself is a nest.js mono ...

Adding TypeScript to your Vue 3 and Vite project: A step-by-step guide

After setting up my project by installing Vue and Vite using the create-vite-app module, I decided to update all the packages generated by 'init vite-app' to the latest RC versions for both Vue and Vite. Now, I am interested in using TypeScript ...

Quote the first field when parsing a CSV

Attempting to utilize Papaparse with a large CSV file that is tab delimited The code snippet appears as follows: const fs = require('fs'); const papa = require('papaparse'); const csvFile = fs.createReadStream('mylargefile.csv&apo ...

Issue with redirecting to another link in Angular routing

After numerous attempts, I finally managed to configure the adviceRouterModule correctly. Despite extensive research and Google searches, I couldn't quite crack it. Here is the configuration for my AdviceRoutingModule: const adviceRouters: Routes = ...

lines stay unbroken in angular

I am encountering an issue when I execute the following code: DetailDisplayer(row) : String { let resultAsString = ""; console.log(row.metadata.questions.length); (row.metadata.questions.length != 0 )?resultAsString += "Questions ...

An error in Webpack prevents it from resolving the data:text import

I built an app that relies on a third-party library with the following syntax: const module = await import(`data:text/javascript;charset=utf-8,${content}`); While using Webpack to build the app, I encountered this error: ERROR in ./node_modules/@web/test- ...