Develop a custom data structure that enables the inclusion of a singular member within an interface

I am currently working with Typescript version 3.9.x

Let's say I have the following interface:

interface mytype {
    foo: Foo
    bar: Bar
    baz: Baz
}

I aim to create a OnlyOneOfType<T> type that allows only one member within the interface.

For example:

const test1: OnlyOneOfType<mytype> = {foo: 'FOO'}; // Should be valid
const test2: OnlyOneOfType<mytype> = {bar: 'BAR'}; // Should be valid

const test3: OnlyOneOfType<mytype> = {foo: 'FOO', bar: 'BAR'}; // Should fail

Answer №1

Is this the specific type you're referencing?

type EnsureOne<T, Keys extends keyof T = keyof T> = Pick<T, Exclude<keyof T, Keys>> &
    {
        [K in Keys]-?: Required<Pick<T, K>> & Partial<Record<Exclude<Keys, K>, undefined>>;
    }[Keys];

type OneOfTypeOnly<T> = EnsureOne<T, keyof T>

interface myInterface {
    apple: 'APPLE'
    orange: 'ORANGE'
    banana: 'BANANA'
}

const check1: OneOfTypeOnly<myInterface> = { apple: 'APPLE' }; // PASS
const check2: OneOfTypeOnly<myInterface> = { orange: 'ORANGE' }; // PASS
const check3: OneOfTypeOnly<myInterface> = { apple: 'APPLE', orange: 'ORANGE' }; // FAIL

This mirrors KPD's solution that can be found in the following question...url

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

What is the reason behind the absence of possibly undefined value in the return from a generic dictionary type in Types

Encountered an unexpected behavior with Typescript I've been using a pattern to define a dictionary of string keys mapped to Foo values like this: type Dictionary = { [id: string]: Foo } What caught me off guard is that when attempting to access a ...

Can SignalR be achieved without using jQuery libraries?

Is TypeScript exclusively for developing SignalR web applications, or is jQuery required? Is there a specific TypeScript version of SignalR available? ...

Angular Bootstrap Modal not Displaying

<img id="1" data-toggle="modal" data-target="#myModal" data-dismiss="modal" src='assets/barrel.jpg' alt='Text dollar code part one.' /> <div id="myModal" class="modal fade" *ngIf="isModalShowing"> <div class=" modal-lg ...

The Nextjs application folder does not contain the getStaticPaths method

I encountered a problem with the latest nextjs app router when I tried to utilize SSG pages for my stapi blog, but kept receiving this error during the build process app/blog/[slug]/page.tsx Type error: Page "app/blog/[slug]/page.tsx" does not m ...

$(...).parentElement is not a function - Troubleshooting a Problem with WebDriver IO and TypeScript

Alright, the objective is simple. I need to ascend from the root to obtain its parent element. Following the webdriver documentation, it should resemble something like this: it('should retrieve the class from the parent element', async () => { ...

Promise rejection: not as expected

I encountered an issue while using alert messages in my login menu: Runtime Error Uncaught (in promise): false Stack Error: Uncaught (in promise): false Here is the code snippet causing the problem: public login() { this.showLoading() this ...

Creating a TypeScript array of objects that aligns with a specific interface: A step-by-step guide

In the code snippet below, there is a Typescript interface called Product. The goal is to ensure that every object in the products array follows this interface. However, the implementation process has been challenging so far. Various attempts like products ...

When the next() function of bcrypt.hash() is called, it does not activate the save method in mongoose

Attempting to hash a password using the .pre() hook: import * as bcrypt from 'bcrypt'; // "bcrypt": "^1.0.2" (<any>mongoose).Promise = require('bluebird'); const user_schema = new Schema({ email: { type: String, required: tru ...

Encountered a syntax issue within the library code while integrating Material Design with Rails, Webpacker, Typescript, and Angular

I am facing a syntax error in my Rails application, specifically in a large JS file that seems to be generated by webpacker. The error appears to be related to Angular/Material code. Interestingly, when I exclude material design, the error disappears. Here ...

Attempting to integrate WebdriverIO into an Angular Electron application

Context: Currently, I am in the process of implementing the fundamental WebdriverIO example within an Angular Electron App. My application is built on the foundation of the Angular Electron Boilerplate. To set up, I have installed webdriverio and @types/we ...

Utilizing PrimeNG menu items to bind commands to a base class function

I'm struggling to connect a parent class function with my Angular 2 PrimeNG menu options. HTML <p-menu #menu popup="popup" [model]="exportItems"></p-menu> <button type="button" class="fa fa-download" title="Export As" (click)="menu.to ...

Steps for connecting to a property in another component

As a newcomer to Angular, I am exploring new concepts for the first time. I have a custom component called Timeselector with an Apply button whose enable/disable state is determined by validations performed in another custom component called Monthpicker. C ...

Having trouble defining a custom scalar in Apollo GraphQL due to TypeScript typing issues

I'm attempting to apply this TypeScript example: https://www.apollographql.com/docs/apollo-server/schema/custom-scalars#example-the-date-scalar import { GraphQLScalarType, Kind } from 'graphql'; export const dateScalar = new GraphQLScalarTy ...

Obtaining the initial value from an Observable in Angular 8+

Initially, I have a page form with preset values and buttons for navigating to the next or previous items. Upon initialization in ngOnInit, an observable provides me with a list of 3 items as the starting value - sometimes it may even contain 4 items. Ho ...

Incorporate matter-js into your TypeScript project

Upon discovering this file: https://www.npmjs.com/package/@types/matter-js I ran the following line of code: npm install --save @types/matter-js When I tried to use it in the main ts file, an error message appeared: 'Matter' refers to a U ...

Reducing the amount of text displayed on ion-text to a minimum

HTML: <ion-list *ngFor="let message of messages"> <ion-item lines="none" type="button" button="true"> <ion-grid> <ion-row> <ion-col class="message"> <ion-text> ...

The customization of primary and secondary palettes in React MUI5 with TypeScript theme is restricted and cannot

Our design team put together numerous custom palettes and additional properties. While this posed no problem in JS, transitioning to TS has proven to be quite challenging. I managed to prevent any errors from being thrown in the createTheme file, but using ...

What steps are necessary to ensure that this validation is functional when set as a required

I've been trying to implement validation in my app, but I'm facing some issues with getting it to work correctly. My goal is to display a message "email is required" when the user leaves the email input empty (even if they make changes), and show ...

Accepting a JSON array as a JSON object is a feature of Angular 2+

Hey there. I'm currently dealing with a JSON object that showcases arrays as JSON objects inside. This is making it difficult for me to iterate over them. Any suggestions or tips on how to handle this would be greatly appreciated! The image below illu ...

Conditioning types for uninitialized objects

Is there a way to create a conditional type that can determine if an object is empty? For instance: function test<T>(a: T): T extends {} ? string : never { return null } let o1: {} let o2: { fox? } let o3: { fox } test(o1) ...