Can Typescript union be utilized to define field choices?

I am working with a type that can accept either a string or a number as options, defined like this:

type Result = string | number

type ValueData = {
    data: Result
} 

const valueDataSchema = new mongoose.Schema({
    data: {
        type: Result
    }
}); 

My question is, is this implementation legal?

Answer №1

Absolutely, that is a feasible option.

One crucial aspect to consider is the behavior within each of your alternatives.

For instance, you could utilize typeof (along with "is..." methods such as isNaN, isArray, etc.) to validate the parameter and prevent any unforeseen issues.

Check out this link for more information on union types in TypeScript.

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

Exploring the Node environment setup within Nest.js

Currently, I am in the midst of setting up a Nest.js project and seeking an efficient solution for defining the Node environment used by the ConfigService to load environment variables: import { Module } from '@nestjs/common'; import { ConfigSer ...

Trouble with displaying cell content in ag-grid within an Angular application

I have implemented ag-grid in my Angular project and I am trying to redirect to a link when a specific cell is clicked. Currently, I have a new value coming from an API which is nested inside an object in an array. For example, the object is dto-> dat ...

Queries with MongoDB RegEx fail to return any matches if the search string contains parentheses

When trying to implement case-insensitivity using regex, it seems to work well for plain strings. However, if special characters like parenthesis are involved in the search query for the name, the database returns no results. For example, a search for "Pu ...

What is the best way to generate a dummy ExecutionContext for testing the CanActivate function in unit testing?

In my authGuard service, I have a canActivate function with the following signature: export interface ExecutionContext extends ArgumentsHost { /** * Returns the *type* of the controller class which the current handler belongs to. */ get ...

What is the method to receive a JSON response rather than an HTML response following a curl request with Express?

I am developing a simple application with basic CRUD functionality using technologies like Express, Mongoose, and MongoDB. The app allows users to submit a form with Owner, Caption, and ImageURL. Everything works fine when testing locally, but I encountere ...

What significance does the order of BSON type comparison hold?

When I review MongoDB documents, I always come across different operators in queries, such as the one found here. One key point that is consistently mentioned in these documents is the importance of the specified BSON comparison order when comparing diffe ...

Implementing dynamic validation rules in Angular forms

In my code, there is a part where I need to make certain fields required. Initially, only the emailAddress field is required, but under a specific condition (res.isSuccess === true), I also need to set firstName, lastName, and companyName as required. The ...

Encountering type-checking errors in the root query due to the specific types assigned to my root nodes in a GraphQL and TypeScript application built using Express

As I delve into the world of typescript/graphql, I encountered a peculiar issue while trying to define the type for one of my root nodes. The root node in question simply fetches a user by ID in the resolve function, and thus, I assigned the 'type&apo ...

Implement a default dropdown menu that displays the current month using Angular and TypeScript

I am looking to implement a dropdown that initially displays the current month. Here is the code snippet I have used: <p-dropdown [options]="months" [filter]="false" filterBy="nombre" [showClear] ...

How do I retrieve a nested object element based on the value of a specific field in Mongoose?

Below is the teamModelSchema schema that I am working with. var teamMemberModelSchema = new mongoose.Schema({ "email": { "type": String, "required": true, "min": 5, "max": 20 }, "name": { "type": String ...

Error importing Firestore in Firebase Cloud Function

As I work on my cloud function, Firebase Firestore gets automatically imported in the following way: import * as functions from 'firebase-functions'; import { QuerySnapshot } from '@google-cloud/firestore'; const admin = require(&ap ...

I am retrieving data from a service and passing it to a component using Angular and receiving '[object Object]'

Searching for assistance with the problem below regarding my model class. I've attempted various approaches using the .pipe.map() and importing {map} from rxjs/operators, but still encountering the error message [object Object] export class AppProfile ...

Passing a complex variable type in TypeScript to a function without the need to redefine the type

I'm fairly new to working with TypeScript and I've encountered this issue several times. When using tools like Prisma to retrieve data, I often come across values with incredibly complex types. These values contain many attributes, which is perf ...

The MongoDB regex is failing to provide the expected outcome

I'm facing an issue with searching data in MongoDB. I have a table with approximately 5000 entries of data that need to be searched based on multiple columns with specific priority criteria. The first priorities for the search are symbol, name, co_nam ...

Some files are missing when performing an npm install for a local package

My project is structured like this: ├── functions/ │ ├── src │ ├── lib │ ├── package.json ├── shared/ │ ├── src │ | ├── index.ts | | ├── interfaces.ts | | └── validator_cl ...

Generating an instance of an enum using a string in Typescript

Having trouble accessing the enum members of a numeric enum in TypeScript using window[name]. The result is an undefined object. export enum MyEnum { MemberOne = 0, MemberTwo = 1 } export class ObjectUtils { public static GetEnumMembers(name ...

Enhanced VS code typings for Nuxt injected properties

My approach to injecting properties into the Nuxt TS context is as follows: ~/plugins/services.ts import Vue from 'vue'; import { errorService } from '~/services/error'; import { Plugin } from '@nuxt/types' const services: Pl ...

JSON to MongoDB Object Converter

Does anyone know of a tool that can convert Gson to DBOjects for MongoDB, like https://code.google.com/p/mongo2gson/, but in the opposite direction (i.e. gson2mongo)? I am looking to change a valid JSONArray string into a DBObject so that I can insert it ...

Iterate over an array of objects and inspect their attributes

Having an array of objects stored in the in_timings variable, I am attempting to validate specific conditions on these objects in preparation for execution. Despite my efforts, it appears that the loop is running on sections I did not anticipate. in_timi ...

What is the mechanism behind relationships in MeteorJS/Mongodb?

I am uncertain about where to locate this information in the documentation. Is there a way to include additional objects in the User object? For example, if I execute meteor add accounts and receive a complete user collection with a functional user ...