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

Is there a way to implement field validation in a Vue wizard form?

Trying to implement form validation using Joi in a Vue wizard form, but not sure how to set it up correctly. The objective is to control the fields before progressing to the next and final page using the next() method. I want to keep the simplicity of th ...

Steps to make ng-packagr detect a Typescript type definition

Ever since the upgrade to Typescript 4.4.2 (which was necessary for supporting Angular 13), it appears that the require syntax is no longer compatible. Now, it seems like I have to use this alternative syntax instead: import * as d3ContextMenu from ' ...

<Click here to navigate to page 2> await whenClicked={navigation.navigate("page_2")} />

Issue with assigning a 'string' to a parameter in TypeScript while trying to navigate to another screen in React Native. Can anyone help with this error? This problem occurs when we want to navigate to another screen using TypeScript in React Na ...

The object might be undefined; TypeScript; Object

Why is it that the object may be undefined, even though it is hard-coded in my file as a constant that never changes? I've tried using ts-ignore without success. const expressConfig = { app: { PORT: 3000, standardResponse: `Server ...

Struggling to properly test the functionality of my NgForm call in Angular2+

I've been trying to test the login functionality by inputting username and password in an NgForm, but I keep encountering unsuccessful attempts. Is there a vital step that I may be overlooking? Currently, I'm facing this error message: Chrome 6 ...

Having trouble receiving accurate intellisense suggestions for MongoDB operations

Implementing communication between a node application and MongoDB without using Mongoose led to the installation of typing for both Node and MongoDB. This resulted in the creation of a typings folder with a reference to index.d.ts in the server.ts file. In ...

There appears to be an issue with the compilation of the TypeScript "import { myVar }" syntax in a Node/CommonJS/ES5 application

In my Node application, I have a configuration file that exports some settings as an object like this: // config.js export var config = { serverPort: 8080 } Within another module, I import these settings and try to access the serverPort property: // ...

Discovering React Styled Components Within the DOM

While working on a project using Styled Components in React, I have successfully created a component as shown below: export const Screen = styled.div({ display: "flex", }); When implementing this component in my render code, it looks like this ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

Utilizing useClass in Angular's APP_INITIALIZER

Before my application starts up, I require some API data and am currently handling it with APP_INITIALIZER and useFactory. However, I aim to enhance the structure by separating all the code from app.module.ts: app.module.ts import { NgModule} from '@ ...

Using PHPMailer to automate sending a gratitude email

I have successfully implemented a PHPMailer form that sends emails without any issues. However, I am looking to enhance it by sending out 2 emails every time the form is submitted. The first email will contain the form field values and will be sent to myse ...

Storing information upon refresh in Angular 8

When it comes to inter-component communication in my Angular project, I am utilizing BehaviourSubject from RXJS. Currently, I have a setup with 3 components: Inquiry Form Where users enter an ID number to check for summon-related information. This data ...

Issue encountered in ../../../../ Unable to locate namespace 'Sizzle'

Following the execution of npm install @types/jquery, I encountered a compilation issue while running my Angular project with ng serve ERROR in ../../../../../../AppData/Roaming/JetBrains/WebStorm2020.1/javascript/extLibs/global-types/node_modules/@types/j ...

Guide to Implementing Dependency Injection in Angular 2

When working with Angular Components written in TypeScript, it is possible to declare a class member (variable) as a parameter of the constructor. I am curious about the reason for doing so. To clarify, take a look at the examples below. Both achieve the ...

How can you establish a TypeScript project that employs classes shared by both client and server applications?

I am working on a project that consists of two components: ServerApp (developed with nodejs using NTVS) and BrowserApp (an Html Typescript application). My goal is to share classes between both projects and have immediate intellisense support. Can you pr ...

The 'this' context setting function is not functioning as expected

Within my Vue component, I am currently working with the following code: import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, value: any, callback: ...

Is it possible to clean all the fields within a specific form simultaneously?

Currently, I am utilizing express-validator for form validation and sanitization on the server side. Many of the validation and sanitization rules are consistent across multiple fields. For instance, I adhere to the following format: check('field nam ...

Type Error TS2322: Cannot assign type 'Object[]' to type '[Object]'

I'm facing an issue with a code snippet that looks like this: export class TagCloud { tags: [Tag]; locations: [Location]; constructor() { this.tags = new Array<Tag>(); this.locations = new Array<Location>(); ...

Behavior of Shadow DOM role when using the <a> element without an href attribute

Recently, I started working with the shadow DOM and encountered a strange issue: In my Ionic Angular application, there is a text styled like a link in this form (simplified): <a href="${ifDefined(this.href)}">link</a> When testing ...

Encountering difficulty when trying to initiate a new project using the Nest CLI

Currently, I am using a tutorial from here to assist me in creating a Nest project. To start off, I have successfully installed the Nest CLI by executing this command: npm i -g @nestjs/cli https://i.stack.imgur.com/3aVd1.png To confirm the installation, ...