Assign a property name in an interface based on the value of another property

Is there a way to define a list of permitted values for a property name in an interface?

Let's consider an interface as an example:

export interface DashboardRequest {
  name?: string;
  description?: string;
  type: 'foo' | 'bar';
  ['foo' | 'bar']: any;
}

I am looking to limit a property name to the possible values of another property within the same interface.

Although the example above is incorrect, it conveys my intended goal.

What is the appropriate approach to achieve this?

Answer №1

To achieve this, you can utilize a discriminated union along with an intersection to prevent repeating common fields

export type DashboardRequest = {
  name?: string;
  description?: string;
} & (
    { type: 'foo'; 'foo': any } |
    { type: 'bar'; 'bar': any }
  )

let foo: DashboardRequest = {
  type: "foo",
  foo : ""
}

let bar: DashboardRequest = {
  type: "bar",
  bar : ""
}

let err: DashboardRequest = {
  type: "bar",
  foo : "" // error
}

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 proper way to utilize useRef in TypeScript to assign a function to ref?

I am just diving into Typescript and I am looking to assign a function to a ref within a custom hook. My goal is for the function to remain constant throughout renders. Check out the code on CodeSandbox: https://codesandbox.io/s/918l0wro4r function runFu ...

Explaining the functionality of reserved words like 'delete' within a d.ts file is essential for understanding their

I am currently in the process of generating a d.ts file for codebooks.io, where I need to define the function delete as an exported top-level function. This is what my codebooks-js.d.ts file looks like at the moment: declare module "codehooks-js" ...

Custom CSS identifier for interactive MuiButton text element

I've been searching for a CSS selector to target this dynamic date element, which is identified as MuiButton-label. While I can currently locate it using xpath in Playwright code, I'm hoping to find an alternative method using a CSS selector. Tha ...

Angular is experiencing difficulty locating the routing path for the auxiliary `router-outlet`

Exploring the intricacies of routing in Angular to gain a deeper understanding of the concept. Encountering an issue where I am receiving an exception NG04002: Cannot match any routes. URL Segment: 'about' when attempting to click on the About li ...

The solution to enabling Type checking in this scenario is simple: Begin by addressing the issue of "Not assignable," followed by resolving any

After subscribing to an observable projected by a BehaviorSubject from a service, I encountered the following errors when trying to assign the subscribed value to a local variable: error TS2322: Type '{}' is not assignable to type 'DatosAdmi ...

What is the process for configuring React on one server and springboot on a separate server?

Can you help me with the setup of the following: Web Server : I need to set up a react + typescript application using npm at Backend Server : I also need to configure a Springboot backend server at I am currently using webpack to build the react applica ...

Encountering an issue with React Redux and Typescript involving the AnyAction error while working on implementing

While integrating redux-persist into my React project, I encountered an error. Previously, Redux was working smoothly, but upon the addition of redux-persist, I started receiving this error message: Types of property 'dispatch' are incompatib ...

Understanding the Union Type in Typescript and Its Application in Angular Development

I came across this piece of code: interface Course { code: string; name: string; user: number | { id: number; name: string; }; } This indicates that a course object can contain either the user object or the user key. When fetching the cour ...

I am encountering an issue in Vue3 where the parent event handler arguments are not being typed with the child's defineEmits definition. Can anyone explain this to me

I am struggling to correctly type the parent event handler based on the child definition, but no matter what I try, I always end up with `any` as the event type. Here is a code example: <script setup lang="ts"> // Child component type Even ...

The data set in a setTimeout is not causing the Angular4 view to update as expected

I am currently working on updating a progress bar while importing data. To achieve this, I have implemented a delay of one second for each record during the import process. Although this may not be the most efficient method, it serves its purpose since thi ...

To run multiple environments with react-native-dotenv in a React Native project using Typescript, only the local environment is activated

Currently, I am facing an issue while trying to initialize my React Native app with TypeScript in three different environments - development, local, and testing. When I attempt to run APP_ENV=testing expo start or APP_ENV=development expo start, it always ...

Encountered an issue during the Jest test where the error message states 'Cannot call Class constructor Stack without using the keyword 'new''

I have encountered an issue with my Jest test for an AWS CDK configuration import { expect as expectCDK, matchTemplate, MatchStyle } from '@aws-cdk/assert'; import * as cdk from '@aws-cdk/core'; import { KmsMultiregionPrincipalKey } fro ...

Angular - Electron interface fails to reflect updated model changes

Whenever I click on a field that allows me to choose a folder from an electron dialog, the dialog opens up and I am able to select the desired folder. However, after clicking okay, even though the folder path is saved in my model, it does not immediately s ...

An informative step-by-step approach to constructing Angular applications utilizing npm and TypeScript

When I first encountered Angular2, I was introduced to TypeScript, npm, and more for the very first time. I was amazed by their power, but I know I've only scratched the surface. While I can navigate through the "development mode," my ultimate goal i ...

Why is it that the component passed in props fails to function properly when invoked as a function? React is signaling a shift in the order of Hooks being called

Here is a simple example I've prepared to illustrate how I am passing a component and then calling it like a function, as well as another example where it works just by calling it normally. You can switch between the working and not working examples b ...

What is the process for creating a new Object based on an interface in Typescript?

I am dealing with an interface that looks like this: interface Response { items: { productId: string; productName: string; price: number; }[] } interface APIResponse { items: { productId: string; produc ...

Exploring Angular 2's nested navigation using the latest router technology

Is there a way to implement nested navigation in Angular? I had this functionality with the previous router setup. { path: '/admin/...', component: AdminLayoutComponent } It seems that since rc1 of angular2, this feature is no longer supported. ...

What's the best way to reset the `react-google-recaptcha` checkbox in a redux application following the submission of a form?

My Redux application consists of two files: LoginForm (which contains the form elements) and LoginFormContainer (which manages form values using Formik). I am facing an issue with resetting the captcha, as the ref is located in the LoginForm file. I attemp ...

Error: Type '() => () => Promise<void>' is not compatible with type 'EffectCallback'

Here is the code that I'm currently working with: useEffect(() => { document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)'; window.$crisp.push(['do', 'ch ...

Exploring depths with Typescript recursion

I'm attempting to implement a recursive search in Typescript, but I am encountering an issue where TS is unable to determine the return type of the function. function findDirectory( directoryId: Key, directory: Directory, ) { if (!directory) ret ...