Limit the field type depending on the value of another field

Consider the following scenario:

type ActionType = 
    'action1' |
    'action2' |
    'action3';

interface Action {
    type: ActionType;
    value?: number | Date;
}

Is there a method in typescript to enforce restrictions on the value type based on the type value?

For instance, if type is either action1 or action2, I would like the value field to only accept values of type number, whereas if type is action3, then value should be of type Date.

Although it may not be feasible, it doesn't hurt to ask.

Answer №1

If you want to increase your odds of success, consider using discriminated unions:

type Event = {
    category: 'category1' | 'category2';
    level: number;
} | {
    category: 'category3';
    date: Date;
}

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

Position components in Angular 2 based on an array's values

Hello all, I am a beginner in terms of Angular 2 and currently facing some obstacles. My goal is to create a board for a board game called Reversi, which has a similar layout to chess but with mono-color pieces. In order to store the necessary information, ...

Increase the timestamp in Typescript by one hour

Is there a way to extend a timestamp by 1 hour? For instance, 1574620200000 (Including Microseconds) This is my date in timestamp format. How can I add a value to the timestamp to increase the time by an additional hour? ...

The argument of type 'NextRouter' cannot be assigned to the parameter of type 'Props' in this scenario

In my component, I am initializing a Formik form by calling a function and passing the next/router object. This is how it looks: export default function Reset() { const router = useRouter(); const formik = useFormik(RecoverForm(router)); return ( ...

Do parallel awaits in JS/TS work only on Chrome browsers exclusively?

Encountering a strange issue with promise resolution behavior in JS/TS. Using Node LTS. It seems that the difference lies in whether the promise resolves to a value that is later read in the code or if it's simply fire-and-forget (void response type). ...

Embedded template does not utilize property binding ngif with any directive

I am currently working on an Angular (Angular2 RC4) application and I'm facing some challenges running it with the live server in nodejs. Any suggestions on how to troubleshoot the error showing up in the Chrome console would be greatly appreciated. ...

Pressing the confirm button will close the sweet alert dialog

When pressing the confirm button, the swal closes. Is this the intended behavior? If so, how can I incorporate the loading example from the examples? Here is my swal code: <swal #saveSwal title="Are you sure?" text ="Do you want to save changes" cancel ...

``Is there a specific scenario where the use of getInitialProps is recommended when automatically redirecting from one

Within my application, I have set up an auto-redirect from the root directory '/' to '/PageOne' with the following code: const Home = () => { const router = useRouter(); useEffect(() => { router.push('/pageone', ...

Creating an interface that extends the Map object in TypeScript to maintain the order of keys

After learning that the normal object doesn't preserve key order in TypeScript, I was advised to use Map. Nevertheless, I'm struggling to figure out how to assign values once I've declared the interface. Take a look at my approach: Coding ...

Creating an interface in Dart: Step-by-step guide to defining interfaces similar to TypeScript

Coming from a Typescript background, I used to define object interfaces like this: export interface Locale { login: { title: string; actions: { submit: string; forgot: string; } } } However, in Dart, interfaces are implicit an ...

Redux-toolkit payload does not recognize the specified type

While working on my project, I encountered an issue when using redux-toolkit. I have created the following reducer: setWaypointToEdit: (state, action: PayloadAction<WaypointToEditPayload>) => { let gridPolygonsData: GridPolygonsData; const { ...

Elevate the scope analysis for a function within the Jasmine framework

I have written a few functions within the app component. I am experiencing an issue with increasing coverage in the summary for these component methods. The test cases are functioning correctly, but some lines are not being accounted for in the coverage s ...

changing an array into json format using TypeScript

Looking to convert an array into JSON using TypeScript. How can I achieve the desired result shown below? let array = ['element1', 'element2', 'element3'] result = [{"value": "element1"}, {"value": "element2"}, {"value": "el ...

Oops! The type error is indicating that you tried to pass 'undefined' where a stream was required. Make sure to provide an Observable, Promise, Array, or Iterable when working with Angular Services

I've developed various services to interact with different APIs. The post services seem to be functioning, but an error keeps popping up: ERROR TypeError: You provided 'undefined' where a stream was expected. Options include Observable, ...

Ensure that child components' property types are enforced in TypeScript

I am trying to enforce the type of a property in a child component. I expected the code below not to compile because Child's property name is not correctly typed inside Parent within the app. However, there is no compiler warning displayed. Is there ...

Error: Module '...' or its type declarations could not be located

Recently, I attempted to deploy my next.js app on Vercel, only to encounter an error that read: "Type error: cannot find module '...' or its corresponding type declarations." After some investigation, I suspect this error is related to local modu ...

Errors may arise in Typescript when attempting to block the default behavior of DataGrid onRowEditStop

Hey there! I'm new to posting questions here and could use some help. I'm encountering a minor issue while trying to prevent the default behavior of the "Enter" key in the "onRowEditStop" method of the DataGrid component. Here's my code sni ...

Discover how to capture and process POST form data in Angular originated from external sources

I am currently building a website that utilizes Java for the backend and Angular for the frontend. I have encountered a scenario where external websites may transmit data to my site via POST form submissions. For example, ▼ General    & ...

Challenges with Spreading Props in TextField Component After MUIv4 Upgrade with TypeScript

Latest Material-UI Version: 4.1.0 I'm encountering difficulties in passing props to an abstracted <TextField /> component that I've developed. Below is the snippet of code: PasswordInput.tsx import * as React from 'react' impo ...

How can I display a modal with image options and image selection using Ionic 4?

Currently, I am developing an Ionic 4 Angular application and implementing an Ionic modal feature. I would like to include images in the modal, so that when a user clicks on them, they are displayed. ...

Setting angular variables by assigning form values

My current reactive form setup looks like this: this.editform = new FormGroup({ 'username' : new FormControl(null,[Validators.required]), 'password' : new FormControl(null,[Validators.required]), 'full_name' : ne ...