Develop a child interface within Typescript

I am unsure if the term sub interface is correct, but my goal is to develop an interface that inherits all properties from the super interface except for some optional ones. Despite referring to the TypeScript documentation for interfaces, I was unable to locate the necessary information.

I understand that I could achieve this by manually copying and excluding certain props from the super Interface, however, I am not fond of this approach as it revolves around wrapping a function that necessitates an argument of type T, while also eliminating specific optional properties before passing them on. To simplify, I will provide a basic example below.

interface DefaultParams {
   param1: boolean;
   param2: boolean;
   param3?: boolean;
   ... // along with numerous other properties sourced from the library that I intend to include
}

// note the absence of 'param3' within the SubParams interface

interface SubParams {
   param1: boolean;
   param2: boolean;
   ... // and various other properties derived from the library that I wish to retain
}

type InnerFunction = (params: DefaultParams) => void;
const funcToCall: InnerFunction = thirdPartyLibrary.function;

function wrapperFunction(params: SubParams) {
   funcToCall(params);
}

In essence, my objective is to establish a SubParams interface that seamlessly aligns with DefaultParams, excluding the param3 optional property.

This marks my inaugural query on Stackoverflow, any corrections or additions are greatly appreciated.

Answer №1

To achieve this, you can utilize the Omit function in TypeScript.

interface User {
  name: string;
  age: number;
  gender: "F" | "M";
  phoneNumber: string;
}

interface UserProfile extends Omit<User, "phoneNumber"> {
  address: string;
}

In simple terms, if a variable is assigned as UserProfile, it will contain properties like name, age, gender, and address while excluding phoneNumber.

If you need further information, you can refer to this link.

Omit

This function creates a new type by selecting all properties from Type and then eliminating specified Keys (as string literals or a union of string literals).

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 Unusual Behavior of Typescript Partial Interfaces

While reviewing the code in a repository I am currently working on, I stumbled upon something that seemed completely incorrect. Here is a snippet of what caught my attention. interface Car { make: string model: string } type SomeType = Partial<Car& ...

Retrieving information from Next.js and Typescript with the help of getStaticProps

I've been working on a personal project with Next.js and TypeScript. I'm attempting to fetch data from an API and then map the items, but I'm running into issues. When I use console.log, it returns undefined. The file is located in the pages ...

When the button is clicked, (ngSubmit) will be triggered

In my Angular2 Form Component, I have implemented two buttons with different functionalities. Button Submit: This button submits all the values to the API. Button Add: This button adds an object to an array. Here are the two methods: onSubmit() { this. ...

Tips for widening a union data type in a different section?

Is there a way to expand on a union type from another module? Below is an example showcasing the need for this, but I encountered a ts(3200) error due to duplicate identifiers. The Core module @org/core defines a union type called OptionType: // Defined i ...

How can I receive the response from a GET request using React Query? I am currently only able to get the response

I have created a search component where I input a name in the request, receive a response, and display it immediately. However, after the first input submit, I get undefined in response. Only after the second submit do I get the desired response. The tec ...

Guide to sending a HTTP POST request with parameters in typescript

I need assistance sending a POST request using parameters in the following format: http://127.0.0.1:9000/api?command={"command":"value","params":{"key":"value","key":"value","key":"value","key":value,}} I attempted to do this but encountered an issue: l ...

Removing the AM and PM from OwlDateTime in Angular is simple since the time format is already in 24-hour time

Using OwlDateTime in a 24-hour format: <div *ngIf="isSchedule" class="form-inline"> <label style='margin-right:5px ;margin-left:210px'> Date Time: <input [owlDateTimeTrigger]="dt" [owlDateTime]="dt" class="form-control" placeh ...

Incorporating TypeScript into a project originally developed in JavaScript

I'm considering using TypeScript to write code for a JavaScript project. I've come to appreciate the benefits of TypeScript and am especially interested in using it for our AngularJS 1.5 project, which we plan to migrate soon. As I'm new to ...

Resolving the "Abstract type N must be an Object type at runtime" error in GraphQL Server Union Types

Given a unique GraphQL union return type: union GetUserProfileOrDatabaseInfo = UserProfile | DatabaseInfo meant to be returned by a specific resolver: type Query { getUserData: GetUserProfileOrDatabaseInfo! } I am encountering warnings and errors rel ...

Issue with TypeScript in Vue3: Unable to access computed property from another computed property

In my Vue3 project with TypeScript, I am encountering an issue where I am unable to access the properties of the returned JavaScript object from one computed property in another computed property using dot notation or named indexing. For instance, when tr ...

What is the most efficient way to retrieve a single type from a union that consists of either a single type or an array of types

Is there a way to determine the type of an exported union type by extracting it from an array, as illustrated in the example above? How can this be achieved without directly referencing the non-exported Type itself? interface CurrentType { a: string; b ...

Typescript: parameter must be included if another is also required

In the user interface, the parameter c is mandatory only if the parameter a is set to true. interface IArguments { a: boolean, b: string, c: string } The solution below seems to be effective, but how can I exclude the c parameter in the first scenar ...

Adding pixels to the top position with jQuery in Angular 2

I am trying to adjust the position of my markers when the zoom level is at 18 or higher by adding 10px upwards. However, my current approach doesn't seem to be working as expected. Can someone please assist me with this issue? You can view the code sn ...

Error: Module 'redux/todo/actions' could not be located. Please check the file path

Despite reading numerous posts and articles on getting absolute imports to work in a TypeScript project, I have not encountered any issues with this. My project is functioning properly with absolute imports. However, within VS Code, all absolute imports a ...

What is the reason behind TypeScript requiring me to initialize a property even though I am retrieving its value from a local reference?

I am just beginning to explore Angular. This is the template for my custom component: <div class="row"> <div class="col-xs-12"> <form action=""> <div class="ro"> <d ...

React-bootstrap-table Axios delete operation causing [object%20Object] to be displayed in the browser console

I am having trouble executing a delete operation using axios on a react-bootstrap-table, and encountering this error in the console DELETE http://localhost:9000/api/terminals/[object%20Object] Uncaught (in promise) Error: Request failed with status cod ...

cookies cannot be obtained from ExecutionContext

I've been trying to obtain a cookie while working with the nestjs and graphql technologies. However, I encountered an issue when it came to validating the cookies by implementing graphql on the module and creating a UseGuard. It was suggested that I ...

What is the best way to inject services into non-service class instances in Angular 2?

Here is my current approach, but I'm curious about the recommended practice for working with Angular2? ... class MultitonObject { _http: Http; constructor (appInjector: Injector) { this._http = appInjector.get(Http); } } var ap ...

Uncover the solution to eliminating webpack warnings associated with incorporating the winston logger by utilizing the ContextReplacementPlugin

When running webpack on a project that includes the winston package, several warnings are generated. This is because webpack automatically includes non-javascript files due to a lazy-loading mechanism in a dependency called logform. The issue arises when ...

Issues encountered when setting up a Context Provider in React using TypeScript

I am currently in the process of setting up a Cart context in my React TypeScript project, inspired by the implementation found here: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js. I'm encountering some conf ...