Make sure the subset interface is selected from the interface / Choose PickDeep<>?

I am searching for a solution using the following interface:

interface Person {
  age: number,
  name: string,
  hometown?: {
    city: string,
    zip: number
  }
}

type SubPerson = EnsureSubInterface<Person, {
  name: string
}>

an example that would be accepted:

const x: SubPerson {
  name: "Tom"
}

an example that would be rejected:

const x: SubPerson {
  age: 12
}

Answer №1

If the goal is to ensure that the second type parameter is a subset of the original at any given level, you can implement this using DeepPartial as a constraint on the second parameter for EnsureSubInterface

type DeepPartial<T> = {
    [P in keyof T]?: T[P] extends Array<infer U>
    ? Array<DeepPartial<U>>
    : T[P] extends ReadonlyArray<infer U>
        ? ReadonlyArray<DeepPartial<U>>
        : DeepPartial<T[P]>
};

type EnsureSubInterface<T, U extends DeepPartial<T>> = U

interface Person {
    age: number,
    name: string,
    hometown?: {
        city: string,
        zip: number
    }
}

type SubPerson = EnsureSubInterface<Person, {
    name: string,
    hometown: {
        city: string,
    }
}>


type NotSubPerson = EnsureSubInterface<Person, {
    name: string,
    hometown: {
        city: number, // error
    }
}>


type NotSubPerson = EnsureSubInterface<Person, {
    name: string,
    hometown: {
        City: string, // error
    }
}>

Depending on your tslint config you might want to make these modifications:

type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends (infer U)[]
  ? DeepPartial<U>[]
  : T[P] extends ReadonlyArray<infer U>
      ? ReadonlyArray<DeepPartial<U>>
      : DeepPartial<T[P]>
};

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

Setting a blank value or null equivalent to a field: Tips and tricks

Here is the component state that I am working with: interface Person { name: string; surname: string; } interface CompState{ //...fields ... person?: Person; } render() { if(this.state.person){ const comp = <div>{this. ...

What is the process for including a new attribute in NextRequest categories?

I'm currently working on a middleware that will introduce a new "name" property to NextRequest. This specific property is intended for use in other sections of the API. import { NextRequest, NextResponse } from 'next/server' export function ...

I can't figure out why the option value is being displayed as "2: Object" when printing it. Can someone please clarify

Hey there! Currently, I have a UI built using Angular 5 and TypeScript. In one of my components, I have a reactive form with a select box form control in the view. What I'm trying to achieve is that whenever a different option is selected from the sel ...

Issue with auto formatting quotes in IntelliJ / WebStorm is no longer functioning as expected

Currently, my TSLint configuration is set to permit the use of single quotes (') instead of double ones ("). Previously, I was able to conveniently switch all instances of " to ' in a file by using the Reformat Code shortcut CTRL + ALT ...

How to dynamically assign a type based on a single choice from multiple options (props)

I have a props object that includes: { option1, option2, option3, option4, general, otherProps } The requirement is to allow only one option to be used at a time. Here are the types defined: interface MyTypes { option1: boolean option2: boolean option3 ...

The @Input directive is failing to receive any data from its parent component

Recently, I delved into the workings of Angular's @Input feature and have found it quite useful thus far. My database is Firebase, and the data snippet I am fetching looks like this: { "page_area_business_image" : { "expand" : { ...

Issue with vertical cell alignment in MUI x-data-grid persists following the latest update to version 7.2.0

After updating my MUI app to the latest npm packages version, specifically upgrading x-data-grid from 5.17.9 to 7.2.0, I encountered an issue. In my application, I utilize a grid where certain columns are populated using the renderCell property: const cel ...

Determine the type of sibling parameter

Creating a Graph component with configurations for the x and y axes. The goal is to utilize GraphProps in the following manner: type Stock = { timestamp: string; value: number; company: 'REDHAT' | 'APPLE' | ... ; } const props: ...

What could be causing NgModel to fail with mat-checkbox and radio buttons in Angular?

I am working with an array of booleans representing week days to determine which day is selected: selectedWeekDays: boolean[] = [true,true,true,true,true,true]; In my HTML file: <section> <h4>Choose your days:</h4> <mat-che ...

Ways to dynamically manipulate HTML elements in Angular 5

Recently, I've been attempting to programmatically transform an HTML element. Strangely, when I update the transform value in the console tab, it changes successfully, but for some reason it doesn't reflect in the element tab of the browser. onD ...

Incorporating a sidemenu into a DOM using Ionic2 and Angular2 Typescript

I am currently struggling to properly integrate the sidemenu from the app.ts file. app.html: <ion-menu [content]="content"></ion-menu> <ion-nav id="nav" [root]="rootPage" #content ></ion-nav> app.ts import {App, IonicApp,Page, ...

Is it possible to run NestJS commands without relying on npx?

I recently installed nestjs using npm, but I encountered an issue where it would not work unless I added npx before every nest command. For example: npx nest -v Without using npx, the commands would not execute properly. In addition, I also faced errors ...

When tests/** are not included in the tsconfig, the TS language features in Vscode become inaccessible

I am looking to configure my TypeScript tests in such a way that they receive linting, code completion, and VSCode intellisense (TypeScript language features) when the test folder is placed next to the src folder. However, I want to ensure that my tests do ...

The cucumber_report.json file will not update to reflect the most recent test steps

I have encountered an issue with the cucumber_reporter.json file not overwriting under the reports/html folder in my framework. To address this, I made changes to the cucumberOpts option within my config.ts file. By modifying the format setting to "json:./ ...

Every time I make updates, I have to reload the page to see the changes take effect

Currently, I am in the process of developing a web application that utilizes Firebase Firestore as the backend and NoSQL database, with Angular serving as the frontend. With frequent updates and changes being made to the website, it becomes cumbersome to c ...

Context API is failing to work in components that use children when the version is v16.6.0 or higher

Currently, I am utilizing the latest context API of React (v16.6.0 or higher) by specifying the public static contextType inside the component that consumes the context. Everything works smoothly unless the component declaring the Provider directly include ...

Tips for coding in Material-UI version 5: Utilizing the color prop in the Chip component by specifying

Is there a better way to type the MUI Chip prop color when the actual value comes from an object? Using any doesn't seem like a good option. Additionally, is keyof typeof CHIP_COLORS the correct approach for typing? import { Chip, Stack } from "@ ...

What is the best way to verify a numerical input in a React component?

When I use the return statement, I attempt to validate a number and if it's not valid, assign a value of 0. However, this approach doesn't seem to be working for me. Is there an alternative method to achieve this? return ( <Input col ...

What is the best method to completely uninstall Apollo-Angular along with all of its dependencies?

Once I added apollo-angular and @apollo/client to my project, I quickly realized that I no longer needed them. However, simply using "npm uninstall apollo-angular" and "npm uninstall @apollo/client" only removed the main folders but left behind other Apoll ...

Form submission returns JSON data with an undefined value from the server

I've been following a tutorial here but ran into some issues due to using newer versions of Angular and Ionic. This is an excerpt from my code: createReview(review){ let headers = new HttpHeaders(); headers.append('Content-Type&apo ...