TypeScript Partial of Union raises an error when trying to assign a value that belongs to a union

My goal is to develop TypeScript interfaces for a query object.

interface Comparison {
    op: '=' | '>' | '<';
    field: string;
    value: any;
}

interface Conjunction {
    op: 'and' | 'or';
    queries: Array<Comparison>;
}

type Query = Comparison | Conjunction;

The query structure can either be simple (Comparison) like

{
    "op": "=",
    "field": "score",
    "value": 5
}

or more complex (Conjunction) like

{
    "op": "and",
    "queries": [
        {
            "op": ">",
            "field": "score",
            "value": 1
        },
        {
            "op": "<",
            "field": "score",
            "value": 10
        }
    ]
}

I am mapping an input filter object into my query object.

// One possible input for a simple comparison filter
// const inputFilter = {
//     field: 'someField',
//     type: 'eq',
//     value: 'someValue'
// };

// An input for a more complex filter
const inputFilter = {
    field: 'someField',
    type: 'range',
    value: 5,
    valueEnd: 10
};

const query: Partial<Query> = {
    field: inputFilter.field
};

switch (inputFilter.type) {
    case 'eq':
        query.op = '=';
        query.value = inputFilter.value;
        break;
    case 'range':
        query.op = 'and'; // ERROR: Type '"and"' is not assignable to type '"=" | ">" | "<" | undefined'
        query.queries = [
            { field: inputFilter.field, op: '>', value: inputFilter.value },
            { field: inputFilter.field, op: '<', value: inputFilter.valueEnd }
        ]; // ERROR: Property 'queries' does not exist on type 'Partial<Comparison>'
        break;
    // ...other cases / default...
}

Two errors occur. The first one when I set query.op to 'and'

Type '"and"' is not assignable to type '"=" | ">" | "<" | undefined'

The second one when trying to set query.queries

Property 'queries' does not exist on type 'Partial<Comparison>'

You can see the code in action on the TypeScript Playground.

Is my understanding of Partial<Query> incorrect? I believed it indicated having a partial comparison or conjunction object.

Just to note, using

Partial<Comparison> | Partial<Conjunction>
also does not work.

Answer №1

Conjunction elements do not contain a field attribute

interface Conjunction {
    op: 'and' | 'or';
    queries: Comparison[];
}

const searchQuery: Partial<Query> = {
    field: inputFilter.field
};

This indicates that your query will consistently be classified as a Comparison.

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

typescript error caused by NaN

Apologies for the repetitive question, but I am really struggling to find a solution. I am facing an issue with this calculation. The parameters a to g represent the values of my input from the HTML. I need to use these values to calculate a sum. When I tr ...

Steps for resolving the error message: "An appropriate loader is required to handle this file type, but there are no loaders currently configured to process it."

I am encountering an issue when working with next.js and trying to export a type in a file called index.ts within a third-party package. Module parse failed: Unexpected token (23:7) You may need an appropriate loader to handle this file type, current ...

Error encountered: Dev server does not have an interface defined

I recently utilized the react-ts template to create a project with vite v5. However, when I run the application using pnpm dev, an error message pops up: App.tsx:9 Uncaught ReferenceError: CharacterConnectionStatus is not defined at App.tsx:9:22 Look ...

Resetting the initial values in Formik while utilizing Yup validation alongside it

Currently, I am working on a React application with Typescript and using Formik along with Yup validation. However, I have encountered an issue with setting values in a Select element. It seems that the value is not changing at all, or it may be resettin ...

Simplify typing in TypeScript using default generic parameters

Imagine I came across the following object: const inquiries = { whoCreatesIssues: { options: { sameTeam: { id: 'SAME_TEAM' }, management: { id: 'MANAGEMENT' ...

``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', ...

oidc-client-js failing to display all profile claims that are supported by oidc-client-js

When setting up UserManager on the oidc-client-ts TypeScript module using the config object below: var config = { authority: "https://localhost:3000", client_id: "js", redirect_uri: "https://localhost:3001/callback.ht ...

Tips for utilizing the polymorphic feature in TypeScript?

One of the challenges I am facing involves adding data to local storage using a function: add(type: "point" | "object", body: FavouritesBodyPoint | FavouritesBodyObject) { // TODO } export interface FavouritesBodyPoint {} export in ...

Managing simultaneous edits to shared data among multiple users using Angular 4

Is it possible to handle multiple users editing the same information, such as editing a patient using two browsers or users simultaneously? One browser starts the edit process, makes changes and saves them. Meanwhile, another browser attempts to make diffe ...

The header remains unchanged even after verifying the user's login status

Currently, I am using Angular 11 for the front-end and Express for the back-end. I am facing an issue with determining if a user is logged in so that I can display the correct header. Even after logging in and setting a cookie in the browser upon redirecti ...

Guide to uploading a recorded audio file (Blob) to a server using ReactJS

I'm having trouble using the react-media-recorder library to send recorded voice as a file to my backend. The backend only supports mp3 and ogg formats. Can anyone provide guidance on how to accomplish this task? Your help would be greatly appreciated ...

Exploring the relationship between two entities in Angular 7 using Typescript

Creating a Reactive form for user registration in Angular involves setting up the form data object separately from the viewmodel object. https://i.sstatic.net/ERlYa.png export interface RegisterViewModel { UserName: string; Email: string; Password: strin ...

Guide to sending jQuery data back to main class in TypeScript

Hi everyone, I'm diving into the world of typescript and JQuery. I have a simple question. In my typescript class called DatePicker, I am calling a function. Here's a snippet of the code: Class DatePicker { private pickerData; public update( ...

What is the reason behind the slight difference between TypeScript's IterableIterator<> and Generator<> generics?

In TypeScript version 3.6.3, there is a notable similarity between Generator<> and IterableIterator<>. However, when Generator<> extends Iterator<>, the third generic argument (TNext) defaults to unknown. On the other hand, Iterator ...

Leverage the power of dynamic type implementations within Angular framework

Recently, I developed a typescript module that contains type definitions and JavaScript implementations in the dist folder. This typescript module serves as an npm package dependency hosted on an internal HTTP link. Below is a basic diagram depicting the c ...

Prevent the event listener from continuously triggering

I have a situation where every time I create an Angular component, an event listener is added. However, upon leaving the page and returning to it, a new event listener is added because the constructor is called again. The problem arises when this event is ...

Attempting to transfer a username String from the client to the server using React and Typescript

I am working on a project where I need to send the username of a logged-in user from the Client to the Server as a string. Currently, I am able to successfully send an image file, but now I also need to send a string along with it. What I aim to do is repl ...

Error in TypeScript: Cannot declare block-scoped variable 'fetch' more than once

Currently, I am in the process of creating a proof of concept where I need to fetch some basic JSON data from JSON-server for display in my react app. While attempting to directly call fetch to retrieve the data, I encountered the following error message: ...

How can I replace the index.d.ts file from a third-party library in Typescript with my own custom definitions?

Currently, I am faced with an issue regarding a third-party JavaScript library that includes an index.d.ts file. Unfortunately, this file is not compatible with my TypeScript version. After coming up with a fix that works for me, I have submitted it to the ...

Error: 'Target is not found' during React Joyride setup

I am attempting to utilize React Joyride on a webpage that includes a modal. The modal is supposed to appear during step 3, with step 4 displaying inside the modal. However, I am encountering an issue where I receive a warning message stating "Target not m ...