Determine if the "type" field is optional or mandatory for the specified input fields in Typescript

I need to determine whether the fields of a typescript type or interface are optional or required.

export type Recommendation = {
    id?: string,
    name: string,
    type?: string,
    tt: string,
    isin?: string,
    issuer: string,
    quantity?: number,
    recDate: string,
    createDate: string,
    buyPrice?: number,
    currentPrice?: number,
    performance?: number,
    comment?: string,
    updateDate?: string,
    updateRec?: string,
    recentRec?: string,
}

For instance, "name" and "issuer" are required, while most other fields are optional.

I have created dynamic input fields for a submit form and I want to dynamically set the "required" attribute on those inputs based on the requirements of the Recommendation type.

        <Table responsive>
            <thead>
                <tr>
                    <th>#</th>
                    <th colSpan={10}>Create new data</th>
                </tr>
            </thead>
        
            <tbody>
                <tr>
                    <td>1</td>
                    {Array.from(Object.keys(sr)).map((colName, index) => (
                        <td key={index}><input required={Recommendation.hasOwnProperty(colName)} name={colName} style={{width: "150px"}} type="text" placeholder={JSON.stringify(colName)} onChange={e => setFieldObj(e)} value={inputValue[colName]}></input></td>
                    ))}
                </tr>
            </tbody>
        </Table>
      <button onClick={submitNewRecord}>Submit</button>

Is there a way to achieve this using typescript?

Answer №1

According to @AlekseyL's comments, it is not possible to access type information at runtime. However, there are cases where you can access data at compile-time.

If you divide your type into a constant array of mandatory fields and a type with no optional fields:

export const RequiredFields = ['name', 'tt', 'issuer', 'recDate', 'createDate'] as const;
type RecommendationFields = {
    id: string,
    name: string,
    type: string,
    tt: string,
    isin: string,
    issuer: string,
    quantity: number,
    recDate: string,
    createDate: string,
    buyPrice: number,
    currentPrice: number,
    performance: number,
    comment: string,
    updateDate: string,
    updateRec: string,
    recentRec: string,
};

You can utilize this information to reconstruct Recommendation:

type OptionalFields = Exclude<keyof RecommendationFields, typeof RequiredFields[number]>;
type RecommendationOptional = { [key in OptionalFields]?: RecommendationFields[key] };
type RecommendationRequired = { [key in typeof RequiredFields[number]]: RecommendationFields[key] };
export type Recommendation = RecommendationOptional & RecommendationRequired;

Then, during runtime, you can check if a field is optional by examining that array:

function isFieldRequired(name: string) {
  return RequiredFields.includes(name);
}

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

Strategies for persisting data in React using local storage to ensure information is retained after page refresh

I am attempting to store searched recipes data in local storage so that when the user refreshes, the data from the last searched recipe will still be available. I have tried saving the recipes data to local storage when a new search request is made and se ...

The Next.js website displays a favicon in Chrome, but it does not appear in Brave browser

As I work on my debut next.js website, I am configuring the favicon in index.js like this: <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> </Head> Initially, all my source ...

Is it true that a TypeScript derived class is not allowed to have identical variable names?

Why is it not allowed for TypeScript derived classes to have the same variable name, even if these members are private? Is there another way to achieve this, or am I making a mistake? class ClassTS { private nom: string = "ClassTS"; ...

The TypeScript compiler is indicating that the Observable HttpEvent cannot be assigned to the type Observable

Utilizing REST API in my angular application requires me to create a service class in typescript. The goal is to dynamically switch between different url endpoints and pass specific headers based on the selected environment. For instance: if the environmen ...

What is the process for implementing a version folder for my @types/definition?

Is there a way to access the typings for react-router in my project? My package.json file currently has this dependency: { "@types/react-router": "^4.0.3" } However, it seems to be using the standard index.d.ts file from DefinitelyTyped library which i ...

Exploring the process of handling and returning JSON-encoded form errors within Symfony

I am looking to develop a webservice where I can submit a form and receive a JSON encoded list specifying which field is incorrect in case of errors. Currently, I am receiving a general list of error messages without specific identification of the fields ...

Arranging shapes for varying levels of magnification

Seeking assistance with properly aligning two forms. I have tried using a positioning approach, but the layout gets disrupted when the browser's Zoom level is adjusted. The second button ends up shifting slightly either upwards or downwards. Here is t ...

Is there a way to verify if the object's ID within an array matches?

I am looking to compare the ID of an object with all IDs of the objects in an array. There is a button that allows me to add a dish to the orders array. If the dish does not already exist in the array, it gets added. However, if the dish already exists, I ...

Creating a Custom Select Option Component with Ant Design Library

Is it possible to customize options in an antd select component? I have been trying to render checkboxes alongside each option, but I am only seeing the default options. Below are my 'CustomSelect' and 'CustomOption' components: // Cu ...

Solve the issue of aligning two contents side by side using Bootstrap

I'm struggling to display two content items in one row. Here's my code snippet: <div class="row"> <div class="form-group"> <div class="col-lg-1"> <label>Insured First ...

I am currently experiencing a problem with deleting documents in Firebase Firestore using React, Typescript, and Redux. Despite the code running, the document continues to exist in

I seem to be encountering an issue that I can't quite figure out. Despite my code running smoothly, I am unable to delete a document from Firestore. The document ID definitely exists within the database, and there are no subcollections attached to it ...

Tips on utilising the datepicker solely with the calendar icon, avoiding the need for any input fields

I'm currently working on a Datatable filter and I would like to incorporate a calendar icon to facilitate date filtering by simply clicking on the Datatable Header. At this stage, I've managed to display a calendar Icon on my Datatable header, b ...

"Concealing a column in a PrimeNG data table with dynamic columns: A step-by-step

Hi, I'm looking for a way to hide a column in my PrimeNG data table. Is there an attribute that can be used to turn off columns in PrimeNG data tables? .Html <p-dataTable emptyMessage="{{tbldatamsg}}" [value]="dataset" scrollable="true" [style]=" ...

Retrieving an Enum member based on its value in TypeScript

I am working with an enum called ABC: enum ABC { A = 'a', B = 'b', C = 'c', } In addition, I have a method named doSomething: doSomething(enum: ABC) { switch(enum) { case A : console.log(A); break; case ...

The variable <variable> is not meeting the 'never' constraint. Error code: ts(2344)

Currently, I am attempting to utilize Supabase alongside TypeScript. However, I encounter an error when trying to use functions like insert(), update(), upsert(), etc. Specifically, the issue arises when declaring the object I want to declare: "Type & ...

The module "ng-particles" does not have a Container component available for export

I have integrated ng-particles into my Angular project by installing it with npm i ng-particles and adding app.ts import { Container, Main } from 'ng-particles'; export class AppComponent{ id = "tsparticles"; /* Using a remote ...

Angular 10 Reactive Form - Controlling character limit in user input field

I'm currently developing an Angular 10 reactive form and I am looking for a way to restrict the maximum number of characters that a user can input into a specific field. Using the maxLength Validator doesn't prevent users from entering more chara ...

Tips for refreshing the 'state' of an Angular Router component

I'm facing an issue with passing data between pages using Angular routing. Everything works as expected when navigating to the "next" page for the first time. However, upon returning to the home page and selecting a different item, the Router's s ...

Is it possible for the binding model of Mat-Checkbox to be optional or null?

Greetings everyone! I am a newcomer to the world of Angular, where I have successfully created a dynamic list of checkboxes. However, I have encountered a challenge when trying to bind selected values from an API to these checkboxes. <div *ngFor="let b ...

Displaying error messages in React Hook Form when passing state

After reviewing the responses below, I have updated my code as follows: import { useState } from "react"; import Head from "next/head"; import Link from "next/link"; import Image from "next/image"; import Background ...