Select one of 2 parameters and begin typing

I recently encountered a situation where I needed to define a type with an id field (string) and an oldId field (number), but I wanted these fields to be exclusive.

For example:

{ id: "1234", name: "foo" }

{ oldId: 1234, name: "bar" }

I attempted the following code:

export type WithIdUnique<T> = T & ({ id: string } | { oldId: number })
export type ProductUnique = WithIdUnique<{
  name: string
}>

const product1Unique: ProductUnique = {
  oldId: 12345,
  name: "foo"
}

const product2Unique: ProductUnique = {
  id: "12345",
  name: "bar"
}

This implementation worked perfectly. However, when passing it as a parameter, I encountered an issue:

import { ProductUnique } from 'product'

export const someTestFunction = (productParam: ProductUnique) => {
  return product.id
}

The error message received was:

Property 'id' does not exist on type 'Product'.

Answer №1

To create the required type, you must combine a never with a union as shown in the example provided below.

The initial part of the type { name: string } serves as the "common" definition, which can consist of one or more properties.

This is then followed by a union of either "an id of type string but never an oldId" OR "an oldId of type number, but never an id". It's important to note that the nevers should have a ? in this scenario.

This pattern proves to be very useful in certain cases.

const product1 = { id: '1234', name: 'foo' };
const product2 = { oldId: 1234, name: 'bar' };
const product9 = { id: '1234', oldId: 1234, name: 'bar' };

type Product = { name: string } & (
  | {
      id: string;
      oldId?: never;
    }
  | {
      id?: never;
      oldId: number;
    }
);

const printProduct = (product: Product) => {
    console.log(product.name);
}

printProduct(product1);
printProduct(product2);
printProduct(product9); // <-- will not be accepted since product9 includes both an id and an oldId

Check Playground here

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

It appears that when importing from a shared package in lerna, the name must include "src" at the end for Typescript or Javascript files

I am currently working on a straightforward lerna project structure as shown below: Project | +-- packages | | | +-- shared | | | | | +-- src | | | | | +-- index.ts | | +-- someDir | | | +-- usesShared | ...

Using RxJs in Angular, you can invoke an observable from within an error callback

I have a scenario where two observable calls are dependent on each other. Everything works fine, but when an error occurs in the response, I need to trigger another observable to rollback the transaction. Below is my code: return this.myService.createOrde ...

In Vue using Typescript, how would I go about defining a local data property that utilizes a prop as its initial value?

When passing a prop to a child component in Vue, the documentation states: The parent component updates will refresh all props in the child component with the latest value. Avoid mutating a prop inside a child component as Vue will warn you in the consol ...

Tips for maintaining the original data type while passing arguments to subsequent functions?

Is there a way to preserve generic type information when using typeof with functions or classes? For instance, in the code snippet below, variables exampleNumber and exampleString are of type Example<unknown>. How can I make them have types Example& ...

Exploring Angular 4: Embracing the Power of Observables

I am currently working on a project that involves loading and selecting clients (not users, but more like customers). However, I have encountered an issue where I am unable to subscribe to the Observables being loaded in my component. Despite trying vario ...

Observables and the categorization of response data

Understanding Observables can be a bit tricky for me at times, leading to some confusion. Let's say we are subscribing to getData in order to retrieve JSON data asynchronously: this.getData(id) .subscribe(res => { console.log(data.ite ...

Tips for obtaining the OneSignal playerID

When launching the app, I need to store the playerID once the user accepts notifications. This functionality is located within the initializeApp function in the app.component.ts file. While I am able to retrieve the playerID (verified through console.log) ...

Guidelines for utilizing a loader to handle a TypeScript-based npm module

I am currently facing a challenge with my React and JavaScript project as I attempt to integrate an npm module developed with TypeScript. The issue lies in configuring my project to compile the TypeScript code from this module, resulting in the error messa ...

What could be causing the table to display empty when we are passing data to the usetable function?

Visit Codesandbox to view Table While the header appears correctly, I noticed something strange. When I console log the data props, it shows all the necessary data. However, when I try to console.log row, there doesn't seem to be any single object re ...

Unable to access or modify properties within a function passed as an argument

deleteDialog(item, func: Function) { this.dialogService .open(ConfirmDialogComponent, { context: { title:"Are you sure?", cancelClss: "info", confirmClss: "danger", }, ...

My customized mat-error seems to be malfunctioning. Does anyone have any insight as to why?

Encountering an issue where the mat-error is not functioning as intended. A custom component was created to manage errors, but it is not behaving correctly upon rendering. Here is the relevant page code: <mat-form-field appearance="outline"> < ...

The introduction of an underscore alters the accessibility of a variable

When working in Angular, I encountered a scenario where I have two files. In the first file, I declared: private _test: BehaviorSubject<any> = new BehaviorSubject({}); And in the second file, I have the following code: test$: Observable<Object& ...

Inoperative due to disability

Issue with Disabling Inputs: [disabled] = true [disabled] = "isDisabled" -----ts > ( isDisabled=true) Standard HTML disabler disable also not functioning properly [attr.disabled] = true [attr.disabled] = "isDisabled" -----ts > ( isDisabled=true) I am a ...

Learn how to merge two objects and return the resulting object using TypeScript functions within the Palantir platform

I am looking to generate a pivot table by combining data from two objects using TypeScript functions. My plan is to first join the two objects, create a unified object, and then perform groupBy operations along with aggregate functions like sum and min on ...

Building a React Redux project template using Visual Studio 2019 and tackling some JavaScript challenges

Seeking clarification on a JavaScript + TypeScript code snippet from the React Redux Visual Studio template. The specific class requiring explanation can be found here: https://github.com/dotnet/aspnetcore/blob/master/src/ProjectTemplates/Web.Spa.ProjectT ...

Material UI TreeView: Organize and present node data with multiple columns in a tree structure

const treeItems = [ { id: 1, name: 'English', country: 'US', children: [ { id: 4, name: 'Spring', country: 'Uk', ...

Experiencing a problem with updating records in angular?

angular version: Angular CLI: 9.0.0-rc.7 I have encountered an issue while trying to update a record. After clicking on the edit icon, I am able to make changes to the record in the form. However, when I click on the Edit Button, the record gets updated i ...

Understanding Typescript event handling in React

Encountering issues when attempting to build my React/Typescript app using the MouseEvent type in an event handler: private ButtonClickHandler(event: MouseEvent): void { ... } The error message received is as follows: error TS2322: Type '{ onCl ...

Accessing the 'comment' property within the .then() function is not possible if it is undefined

Why does obj[i] become undefined inside the .then() function? obj = [{'id': 1, 'name': 'john', 'age': '22', 'group': 'grA'}, {'id': 2, 'name': 'mike', &apo ...

The type is lacking the following properties in array.push

Encountering an issue with the register page in my IONIC app. Currently, I am utilizing a data.json file to store all user data, and I aim to create a new member with minimal information required (name, email, password) while leaving other fields empty fo ...