Creating models of recursive data structures using a combination of classes, subclasses, and recursive generic constraints

I am currently working on creating a binary search tree (BST) and an extended version called Statistic BST that includes an additional size property. While experimenting, I have explored three different approaches:

  1. Using recursion
  2. Implementing polymorphism
  3. Applying bounded polymorphism
// 1. Recursive.
interface IBSTRec<K, V> {
    key: K;
    value: V;
    left?: IBSTRec<K, V>;
    right?: IBSTRec<K, V>;
}

class BSTRec<K, V> implements IBSTRec<K, V> {
    constructor(
        public key: K, 
        public value: V, 
        public left?: BSTRec<K, V>, 
        public right?: BSTRec<K, V>
    ) { /* ... */ }

    insert(node: BSTRec<K, V>): BSTRec<K, V> {
        // Insert logic...
        return node;
    }
}

// more code here...

Answer №1

It is a fact that default type arguments are unable to reference themselves. Nevertheless, types in general can refer to themselves, allowing you to create a new type alias for the desired default and then utilize it.

Therefore, you can transform

interface IBSTBoRec<K, V, 
    T extends IBSTBoRec<K, V, T> = IBSTBoRec<K, V, ???>> {
    key: K;
    value: V;
    left?: T;
    right?: T;
}

to

type IBSTBoRecDflt<K, V> = IBSTBoRec<K, V, IBSTBoRecDflt<K, V>>;

interface IBSTBoRec<K, V,
    T extends IBSTBoRec<K, V, T> = IBSTBoRecDflt<K, V>> {
    key: K;
    value: V;
    left?: T;
    right?: T;
}

This now compiles without errors. While it may or may not fully address your specific requirements, it offers a solution to the self-referential default problem. You can also implement this approach for other defaults in your code example.

Link to Playground with Code

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

Angular is failing to detect a change in the initial element of an array

In my Angular app, I am working on displaying a list of dates for the current week. Users should be able to view previous weeks by clicking a button, so I am using an Observable to update the array of dates and trying to display the updated array. Althoug ...

The art of crafting informative error log messages in Protractor using TypeScript

I am currently utilizing Protractor, written in typescript, to conduct tests on a live website. I am seeking guidance on how to generate log messages when a Protractor test fails. Presently, the only feedback received is a simple YES/NO message, as shown b ...

react state change not triggering re-render of paragraph

I recently started learning react and web development. To streamline my work, I've been using ChatGPT, but I'm facing an issue that I can't seem to solve. I'm trying to fetch movie descriptions from the TMDB API using movie IDs, but des ...

Is it necessary to 'type assert' the retrieved data in Axios if I have already specified the return type in the function declaration?

Consider the code snippet below: import axios from 'axios' async function fetchAPI<T>(path: string, data: any): Promise<T> { return (await axios.get(path, data)).data as T } async function getSomething(): Promise<SomeType> { ...

What is the method for determining the number of properties that share a common value?

After fetching a JSON object from an API, I am currently going through the result set and constructing a ticket object. Here is the link to the JSON data: data.ticket.seating.forEach((seat: any) => { this.listings.push({ section: seat ...

Is there a way to determine the specific child property types of a custom Generic type extension?

I am looking to create a function that can retrieve a property from an extended generic type. Is this something achievable? Here is my attempt: interface Animal { readonly weight: {total: number} } interface Dog extends Animal { readonly weight: ...

What is the proper way to retrieve a constant variable within a return statement?

Here is the code I have written: const keyToDisplayMessage = 'REGULAR_HOME'; const cf = format( { accountName: this.accountName, }, this.pageData.sucessMessages.keyToDisplayMessage, this.$route.name ); return cf; The ...

How can I set a document ID as a variable in Firebase Firestore?

I recently set up a firestore collection and successfully added data (documents) to it. Firestore conveniently generates unique document ids for each entry. Inserting Data this.afs.collection('questions').add({ 'question': message, &a ...

Custom mapped type results in intermediate forms

I've recently developed a type in Typescript that explicitly blocks specific properties from objects/interfaces. This is necessary because Typescript's excess property checking only kicks in when an object literal is directly assigned, not when i ...

Utilizing a class structure to organize express.Router?

I've been playing around with using Express router and classes in Typescript to organize my routes. This is the approach I've taken so far. In the index.ts file, I'm trying to reference the Notes class from the notes.ts file, which has an en ...

Tips for successfully navigating TS type checking for component properties

export const Component: React.FC<SpaProps> = function({ a, b, c, d }) a, b, and c are all part of SpaProps, but d is not. Is there a way to add a prop type that includes all of them together? Also, I already know the type for d. expo ...

Tips for managing script tags within an HTML file in a Chrome extension using TypeScript and webpack

After successfully building a Chrome extension in JavaScript, the decision was made to convert it into TypeScript. This required using webpack and a tsconfig file, along with making necessary changes. The extension loaded without errors, but there are a fe ...

Angular date function - I aim to increase the date by 7 days and showcase it in an HTML format

Received a date from an API in the format: 31-08-2021 13:58. I need to display this date in one mat-cell and then in another cell, adding 7 days to it. For example: 7-09-2021 13:58. How can I achieve this? ...

GraphQL type featuring a union property defined inline

Trying to create a matching GQL type for this Typescript interface: interface List { items: [String] | [[String]] } Initially, I attempted to keep it straightforward: type List { items: [String]! | [[String]!]! } However, GQL did not approve of tha ...

React useContext with TypeScript error: "property is not recognized on '{}'"

I have organized a context to distribute Firebase authentication objects in the following way: export function AuthProvider(props: {children: React.ReactNode}) { const [user, setUser] = useState<IUser>({uid: ""}); useEffect(() => ...

What is the best way to convert an array of Firestore DocumentReferences into an array of DocumentData?

Trying to create a Google Cloud Function that reads Firestore Documents from a collection and takes action based on these documents. The goal is to optimize efficiency by reading the documents once and storing them in an array to minimize read operations. ...

Exploring TypeScript Object Properties in Angular 2

How can I extract and display the ID and title of the Hero object below? The structure of the Hero interface is based on a Firebase JSON response. hero.component.ts import {Component, Input} from 'angular2/core'; import {Hero} from '../mod ...

Guide on importing absolute paths in a @nrwl/nx monorepo

I am currently working on a @nrwl/nx monorepo and I am looking to import folders within the project src using absolute paths. I attempted to specify the baseUrl but had no success. The only solution that did work was adding the path to the monorepo root ts ...

In ReactJS, the way to submit a form using OnChange is by utilizing the

Is there a way to submit a form using Onchange without a button? I need to fire the form but can't insert routes as it's a component for multiple clients. My project is built using react hook forms. const handleChange = (e: any) => { c ...

What is causing this issue in TypeScript version 4.8?

After updating to TypeScript 4.8 in VSCode, I have encountered an error in one of my React projects that was not present before. Strangely, this error does not prevent the code from compiling successfully when building the project. It's challenging to ...