Creating a dynamic list in Typescript from a tuple array without any intersections

const colors = ["red", "blue", "green", "yellow"] as const;
const buttonSizes = ["small", "medium", "large"] as const;
type ColorType = (typeof colors)[number];
type SizeType = (typeof buttonSizes)[number];

type ButtonProperties = {
  color?: ColorType;
  size?: SizeType;
} & {
  [K in ColorType as `${Lowercase<K>}`]?: boolean;
};

This code snippet showcases how a Vue component can accept different properties such as

or like

If you try to define the properties statically, like so:

type ButtonProperties = {
  color?: "red" | "blue" | "green" | "yellow";
  size?: "small" | "medium" | "large";
  red?: boolean;
  blue?: boolean;
  green?: boolean;
  yellow?: boolean;
} 

It might work... but it can become repetitive and cumbersome when iterating over color options.

The initial example works fine, although VUE may throw an error for some reason:

Internal server error: [@vue/compiler-sfc] type argument passed to defineProps() must be a literal type, or a reference to an interface or literal type.

This issue is known and is currently being addressed.

Is there a different approach to dynamically defining the ButtonProperties without using intersections?

Answer №1

When encountering the error message "reference to an interface or literal type", it is suggested that defining ButtonProps as an interface extending a base type should resolve the issue:

type IntentAndSize = {
  [K in IntentType as `${Lowercase<K>}`]?: boolean;
};

interface ButtonProps extends IntentAndSize {
  intent?: IntentType;
  size?: SizeType;
}

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

What is the reason for the manual update of a view when copying an object's attributes into another object, as opposed to using Object.assign()?

In my application, I have a parent component called 'EmployeeComponent' that is responsible for displaying a list of employees. Additionally, there is a child component named 'EmployeeDetailComponent' which displays the details of the s ...

"Exploiting the Power of Nullish Coalescing in Functional

The interface I am working with is defined below: interface Foo { error?: string; getError?: (param: any) => string } In this scenario, we always need to call the function getError, but it may be undefined. When dealing with base types, we can us ...

Exploring methods in Firebase Cloud Functions to retrieve and modify values

I'm currently attempting to retrieve a value from a specific location in my database, add 1 to it, and then update it back. However, I keep encountering various errors, with the most recent being: TypeError: Cannot read property 'update' of ...

Retrieve information from an API and populate a MDBootstrap datatable using Vue.js and Axios

I am looking to populate a mdbootstrap datatable with data from my API. Is there a way for me to create a method that can call the getPosts() API and then write the results into the rows[] array? <template> <mdb-datatable :data="dat ...

VueJs does not display the source code of components for users

I've recently delved into working with vueJS2 and am currently learning about components. I have a question for the experts in this field. As far as I understand, VueJS processes HTML using JavaScript, which is why the rest of the HTML code may not b ...

Exploring the Differences Between ionViewWillEnter and ionViewDidEnter

When considering whether to reinitiate a cached task, the choice between ionDidLoad is clear. However, when we need to perform a task every time a view is entered, deciding between ionViewWillEnter and ionViewDidEnter can be challenging. No specific guid ...

An effective method for adding information to a REDIS hash

My current computing process involves storing the results in the REDIS database before transferring them to the main database. At the moment, I handle operations in batches of 10k items per chunk using a separate GAE instance (single-threaded computing wi ...

What is the best way to initiate the handling of newly inserted values in a Vuex store?

I am working with a Vuex store that stores entries: const store = createStore({ state() { return { entries: [ { id: 1, date-of-birth: "2020-10-15T14:48:00.000Z", name: "Tom", }, ...

``There seems to be an issue with retrieving and displaying data in Ionic2 when using nav

I am facing an issue with displaying the data received from NavParams. I have used console.log() to confirm that I am getting the correct data, but for some reason, I am unable to display it on the new page. I suspect that there might be an error in how I ...

Issue: formGroup requires an input of type FormGroup. Please provide one; Error: Unable to access property 'controls' as it is undefined

In the process of building a login and registration form using Angular with .Net core, I encountered an error upon running the program. The error is showing up in the Browser Console tab. This is my userlog.component.ts file: import { Component, OnInit, O ...

Vuex action method completes without returning a value

I've come across a situation in my Vuex action where the console.log() is displaying an undefined output. Here's the method in my Vuex action: const actions = { async fetchByQuery({ commit, title }) { console.log(title); //other code ...

WindiCSS classes are not functioning properly within a Nuxt application

I've been encountering some difficulties with WindiCSS. The classes are not being applied to the elements as expected. I attempted to install an older version of Windi, but the issue persisted. I even tried switching to Tailwind instead of Windi, but ...

Organize JSON data in Angular 6 from an observable based on a specific key

Note: While I am familiar with sorting a regular array of objects using .sort(), I am facing a challenge with an observable object that I am not accustomed to. My task involves retrieving a JSON array of objects with a service: import { Injectable } from ...

There seems to be a syntax error in the regular expression used in Angular TypeScript

I've encountered an error and I'm struggling to identify the syntax issue. core.mjs:6495 ERROR SyntaxError: Invalid regular expression: /https://graph.microsoft.com/v1.0/communications/callRecords/getPstnCalls(fromDateTime=2020-01-30,toDateTime ...

No types are assigned to any props

I recently began working on a SvelteKit skeleton project for my personal website. However, I encountered an error when using Svelte with TypeScript - specifically, I kept getting the message Type '<some prop type>' is not assignable to type ...

Type returned by a React component

I am currently using a basic context provider export function CustomStepsProvider ({ children, ...props }: React.PropsWithChildren<CustomStepsProps>) => { return <Steps.Provider value={props}> {typeof children === 'function&ap ...

When attempting to transfer data from the parent component to child components, the data is appearing as undefined in the display

I have been working on passing data from a parent component to child components, but I keep encountering an issue where the data is showing as undefined. Below is the code snippet: Parent Component In this section, I have declared the variable part_data ...

Utilizing a loaded variable containing data from an external API request within the useEffect() hook of a React component

Essentially, I have an API request within the useEffect() hook to fetch all "notebooks" before the page renders, allowing me to display them. useEffect(() => { getIdToken().then((idToken) => { const data = getAllNotebooks(idToken); ...

Numerous access points within Vite

I am currently working on a Vue2 project that uses Webpack, and I have decided to make the switch to Vite. Within my webpack.common.js file, there are multiple entry points defined: module.exports = { entry: { appSchool: './resources/scho ...

Exploring VueJS: Sorting objects within an array

Currently, I am tackling a challenge in vue-js. In my codebase, there exists a data object known as items. I am iterating through these items and aiming to present a dropdown menu containing the list of products. My goal now is to showcase only those pro ...