Exclude any objects in a union type that contain keys other than a specified key

Consider a type such as

type Test = { name: "a" } | { name: "b" } | { name: "c", other: 1 } | { name: "d", other: 2 }

Is there a way to selectively remove types from the union that have keys other than "name". For example, in this scenario, the expected result would be { name: "a" } | { name: "b" }.

If interested, you can experiment further on TypeScript Playground by visiting this link: Link to TypeScript Playground

Answer №1

In situations like this, it is common to utilize a distributive conditional type to break down the union input type into its individual members and then selectively keep or discard each member before combining them back into another union. Here's one approach:

type Filter<T> = T extends unknown ?
    Exclude<keyof T, "name"> extends never ? T : never
    : never

The expression T extends unknown ? ⋯ : never distributes over unions in the generic type parameter T. The filter used here is

Exclude<keyof T, "name"> extends never ? T : never
. The utility type Exclude<X, Y> eliminates union members of X that match Y, so Exclude<keyof T, "name"> represents the keys of
T</code that are not named "name." If this set is empty (which means the impossible <code>never
type), we retain T; otherwise, we discard it.

Let's put it to the test:

type Test = { name: "a" } | { name: "b" } |
{ name: "c", other: 1 } | { name: "d", other: 2 }

type FilteredTest = Filter<Test>;
/* type FilteredTest = { name: "a"; } | { name: "b"; } */

let x: FilteredTest = { name: "c", other: 1 } // Error
let y: FilteredTest = { name: "a" } // Fine

Everything seems to be working as expected!

Try out the code yourself in the playground

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

The parameter 'string | JwtPayload' cannot be assigned to the parameter 'string'

Utilizing Typescript alongside Express and JWT for Bearer Authorization presents a specific challenge. In this situation, I am developing the authorize middleware with JWT as specified and attempting to extricate the current user from the JWT token. Sampl ...

Guide on how to navigate within an app by clicking on a link from an email

Is there a way to launch my Android application (Nativescript) from a link in an email that says "Click here to reset password"? For example, the email contains a link like this: When I click on this link from my mobile browser, I want the app to open to ...

Struggling with setting up eslint in my typescript project

Below is the contents of my package.json file: { "devDependencies": { "@typescript-eslint/eslint-plugin": "^5.13.0", "@typescript-eslint/parser": "^5.13.0", "airbnb": "^0.0.2&qu ...

The assignment of Type Observable<Observable<any[]>> to Observable<any[]> is not valid

Working on implementing autocomplete using data from a database service: @Injectable() export class SchoolService { constructor(private db: AngularFirestore) { } getSchools(): Observable<School[]> { return this.db.collection<School> ...

Refresh a reactive form in Angular Material

I'm facing a challenge with resetting my form after data submission. Everything is working except for validating the email format. Using this.form.reset() doesn't seem to resolve the issue. https://i.sstatic.net/QRZEa.png Any suggestions on how ...

How can Angular JS handle multiple validators being triggered at once?

Hey there, I'm currently working with validators in my Angular form setup. Here's a snippet of how it looks - I utilize Validators.compose to combine custom validators. The errors from these validators are then displayed on the HTML component. My ...

The error message "Property <property> is not recognized on the type 'jQueryStatic<HTMLElement>'" is indicating an issue with accessing a specific property within the TypeScript codebase that utilizes Angular CLI, NPM,

My Development Environment I am utilizing Angular, Angular CLI, NPM, and Typescript in my web application development. Within one of my components, I require the use of jQuery to initialize a jQuery plugin. In this particular case, the plugin in question ...

Converting date format from d-mmm-yyyy to yyyy-mm-d using Angular 2

How can I convert the date format from d-mmm-yyyy to yyyy-mm-d using Angular 2's datepipe? I need to change dates like 1-Nov-2019 to 2019-11-1 or 15-Dec-2018 to 2018-12-15 It's essential that I achieve this transformation using the built-in fun ...

What is the best way to capture the inputs' values and store them accurately in my object within localStorage?

Is there a more efficient way to get all the input values ​​and place them in the appropriate location in my object (localStorage) without having to individually retrieve them as shown in the code below? Below is the function I currently use to update ...

determine function output based on input type

Here's a question that is somewhat similar to TypeScript function return type based on input parameter, but with a twist involving promises. The scenario is as follows: if the input is a string, then the method returns a PlaylistEntity, otherwise it ...

A guide on transitioning from using require imports to implementing ES6 imports with the concept of currying

Currently in the process of migrating a Node/Express server to TypeScript. I have been using currying to minimize import statements, but now want to switch to ES6 import syntax. How can I translate these imports to ES6? const app = require("express")(); ...

The error message "ER_BAD_FIELD_ERROR: The column 'table.column' is not recognized in the 'on clause'" is displayed

I am encountering a perplexing issue... I'm attempting to execute a query: SELECT ordenes_servicio.idorden, estatus_orden.descripcion AS estatus, tipo_orden.descripcion AS tipo_orden, usuario.nombre, ordenes_servicio.nombres_cliente, ordenes_servicio ...

Progressive series of observable conditions

The issue at hand: I am faced with the task of checking multiple conditions, some of which lead to the same outcome. Here is the current flow: First, I check if a form is saved locally If it is saved locally, I display text 1 to the user If not saved l ...

Updating the JWT token in Angular 6 and making a new request with the updated token

When my JWT authentication token expires (verified by the backend), I need to call a refresh token API and resend the last failed request due to the expired token. I have an Interceptor in place, but I must update the authentication header before sending ...

The issue arises when the desired image size is not reflected correctly on the background after changing

I've been working on a basic image slideshow where the background image changes based on user selection. However, I've noticed that when I change the image for the first time, the backgroundSize: cover property seems to disappear. Even if I try c ...

I am having trouble with Visual Studio Code and ESLint not recognizing spelling errors such as "style.backgroundCOlor". What steps can I take to resolve this issue?

Since I'm relatively new to Visual Studio Code, I recently encountered an issue with the "ESLint" extension where my typos were not being detected. These typos were in actual pieces of code, not just comments, which made it tricky to spot the errors. ...

``There seems to be an issue with retrieving and displaying data in Ionic2 when using nav

I am facing an issue with displaying the data received from NavParams. I have used console.log() to confirm that I am getting the correct data, but for some reason, I am unable to display it on the new page. I suspect that there might be an error in how I ...

What is the best way to transform a Map<string, boolean> into an array of objects with key-value pairs {key: string, value: boolean

I'm currently working on a React project that incorporates TypeScript, and I've successfully implemented dynamic permission creation on the user creation page by utilizing this particular code snippet. The permissions being used on the page are m ...

Sending a CSS class to an Angular library

In my development process, I am currently working on creating a library using Angular CDK specifically for custom modals. One feature I want to implement is the ability for applications using the library to pass a CSS class name along with other modal conf ...

Having difficulty in accessing the node modules

As a C#/C++ programmer new to nodejs, I am looking to incorporate typescript into my code. However, when attempting to import modules like fs or stream, I am encountering the following error: Module not found Interestingly, VisualStudio 2017 is able to ...