typescript tips for incorporating nested types in inheritance

I currently have a specific data structure.

type Deposit {
    num1: number;
    num2: number;
}

type Nice {
   num: number;
   deposit: Deposit;
}

As of now, I am using the Nice type, but I wish to enhance it by adding more fields to its deposit. Ultimately, I want it to look like this:

type Deposit {
    num1: number;
    num2: number;
    num3: string;
    num4: string;
}

type Nice {
   num: number;
   deposit: Deposit;
}

However, I am unable to modify the existing Deposit or Nice types as they are part of a library.

Answer №1

If you want to create a customized child type, you can do so by utilizing the extends keyword and inserting it in a shared types.ts file. This way, you can import the type from there instead of directly importing it from the library.

// src/types.ts

import { Deposit as DepositBase, Nice as NiceBase } from 'some-lib';

export interface Deposit extends DepositBase {
  num3: string;
  num4: string;
}

export interface Nice extends NiceBase {
  deposit: Deposit;
}

Subsequently, you can implement it like this:

// src/some-lib-wrapper.ts

import * as someLib from 'some-lib';
import { Deposit, Nice } from './types'; // our enhanced types

// You have the capability to "re-type" the library functions within this wrapper module
// in order to make use of our personalized extended types
export function makeDeposit(nice: Nice): Deposit {
  /* invoke someLib.makeDeposit here... */
}
// src/index.ts

import { makeDeposit } from './some-lib-wrapper'; // utilize the version with our modified types
import { Deposit, Nice } from './types';

// Make use of your custom wrapped functions & types
makeDeposit(...);

Answer №2

To add new properties to an existing type, you can create a helper type like this:

type Deposit = {
    num1: number;
    num2: number;
}

type Nice = {
    num: number;
    deposit: Deposit;
}

type ExtendProp<Obj, Prop, NewValue> = {
    [P in keyof Obj]: P extends Prop ? Obj[P] & NewValue : Obj[P]
}

type Result = ExtendProp<Nice, 'deposit', { foo: 'bar' }> // { deposit: Deposit & { foo: 'bar';  };

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

How come the back button does not initiate client-side navigation in a Next.js application?

In my Next.js application utilizing GraphQL to fetch articles from a server, I encountered an issue with dynamic routing when reloading the page while on an article and attempting to navigate back. The usual scenario works as expected: Index -> [slu ...

What is the best method for sending a JavaScript variable to the server and back again?

I'm currently working on a JavaScript project where I need to build a string. Let's say, for the sake of this example: var cereal = 'my awesome string'; There's also a button on my webpage: <button id="send" type="submit" nam ...

Determining the size of the axis in correlation to a set constant length

Basic Concept I am currently developing a small tool designed to assist with geometric calculations for print-related items. Project Overview In this tool, users are asked to input the width and height of a box, represented visually as a CSS-based box, ...

The HTML code as content

While working on an AJAX project, I ran into this issue: http://jsbin.com/iriquf/1 The data variable contains a simple HTML string. After making the AJAX call, I noticed that the returned string sometimes includes extra whitespaces. I attempted to locat ...

Exploring the components of the scene with three.js

I have a desire to explore each element within a particular scene. These elements come in various forms such as THREE.Object3D, THREE.Mesh, and more. Some of these elements contain a property called children, which is essentially an array of other elements ...

How can I properly choose distinct values for an individual attribute from a JavaScript array containing objects?

Let's imagine a scenario with an array of JavaScript objects like this: var data = [ {category : "root", type: "qqqqq", value1: "aaaaa", value2: "zzzzz"}, {category : "root", type: "qqqqq", value1: "aaaaa", value2: "xxxxx"}, {category : " ...

Error thrown when attempting to pass additional argument through Thunk Middleware in Redux Toolkit using TypeScript

I have a question regarding customizing the Middleware provided by Redux Toolkit to include an extra argument. This additional argument is an instance of a Repository. During store configuration, I append this additional argument: export const store = con ...

The layout option is not specified within the ejs-mate package

error boilerplate I am baffled as to why the layout is not being defined. I have installed ejs-mate and ejs, yet it still gives this error. <% layout('layouts/boilerplate') %> <h1>All campgrounds </h1> <div> <a ...

Obtain the textfield whenever the user desires

I have added an image upload file field in the form. If the user wants a multi-select field, I want to allow the user to choose the number of files they want to upload. Take a look at my text field below: <div class="form-group col-lg-10"> {! ...

Troubleshooting: Unable to load template file content in AngularJS ng-view

Setting up a demo angular app has been quite the challenge for me. Despite my efforts, the content from my partial file (partials/test.html) is not loading into the layout file as expected. Below is a snippet of my index.html: <!DOCTYPE html> <ht ...

Encountering issues in the terminal during the installation of React Native

When attempting to install React Native using npm install -g expo-cli, I encountered some errors. I received several deprecation warnings for various packages: [email protected]: This package has been deprecated and now only exports makeExecutableSch ...

Prevent the function from being triggered repeatedly while scrolling

When a user scrolls to the bottom of the page, the following code is meant to load the next page. However, there are instances where it repeats itself due to rapid scrolling or while the AJAX content is still loading. Is there a way to prevent this code f ...

Avoid using single quotes in Postgres queries for a more secure Node.js application

Snippet from my node js code: var qry = 'INSERT INTO "sma"."RMD"("UserId","Favourite") VALUES (' + req.body.user + ',' + JSON.stringify(req.body.favourite) + ')' My problem is inserting single quotes before JSON.stringify(r ...

What is the role of the handleSubmit parameter in React Hook Form?

I'm encountering an issue with TypeScript in the handleSubmit function. To start off, I am accessing the handleSubmit function through the useForm hook: const {handleSubmit, control, watch, reset} = useForm() Next, I define a submit function: con ...

Failure to Fetch the Uploaded File's Value Using the Parameter

Objective: My aim is to automatically upload the second input named "file2" to the action result using jQuery code that is compatible with the latest versions of Firefox, Chrome, and Internet Explorer. Issue: The problem arises when HttpPostedFileBase ...

Retrieving the value of the button with $(this).val() is the only function that newusername performs

My issue arises when trying to send my data to a PHP file; it only sends the value of the <button> or <input type="button">. If I remove the variable definitions, it will only send the data as a string if they are formatted like this: newuser ...

Troubles with Jest tests are encountered when using ts-jest in an ES2020/ESNEXT TypeScript project

Currently, I am working on a VueJS project that utilizes ViteJS for transpilation, which is functioning properly. However, when Jest testing is involved alongside ts-jest, the following Jest configuration is used: jest.config.ts import { resolve } from &q ...

How can I customize a default button in HTML to hide the selected option from the dropdown menu?

Hey there! I'm currently working on a website that needs to be bilingual, with Spanish as the default language. I want to include a dropdown button that allows users to translate the content into English. Here's what I've tried so far: ...

Twists and turns as I mix up Kineticjs

After scrambling my puzzle, I now need it to be rotated. Can anyone help me with this? Thanks :) fillPatternImage:imageObj, x:-pieceWidth*i/2, y:-pieceHeight*j/2, stroke: "#000000", ...

Loop through data and use jQuery to insert it into the server

I am encountering an issue with my code as I attempt to insert data from a loop; unfortunately, I keep getting the error message "Uncaught TypeError: Illegal invocation". window.items = ''; _.forEach(cart.items, function(n, key) ...