Can one assign the type of a sibling property to another property within a nested object?

In search of a solution: I am attempting to develop a function, which we'll refer to as test, designed to handle nested objects with dynamic keys on the first level. The goal is for this function to automatically suggest the type of method without requiring manual input. Additionally, it should also support generic types for other methods and properties being passed in. See the example below for clarification.

type NestedProperties = {
  property: () => any,
  anotherProperty: () => any,
  key: (...args: any) => string[],
  method: (data: ReturnType<Test['property']>) => any,
}

Here's how you can use it:


function test<T extends Record<string, NestedProperties>>(obj: T){}

function key({ productId }: { productId: number }) {
  return [ 'list', { productId } ]
}

test({
  list: {
    property: () => 'string',
    anotherProperty: () => 1, // will not result as () => any.
    key, // this will also not result as (...args: any) => string[]
    method: (data) /* and this will automatically infer type of returntype of list.property*/ {
       ...do something
    }
  }
});

Answer №1

To enhance your code in TypeScript, you can leverage utility types like ReturnType and conditional types. Here's a neat trick to have the type of data parameter inferred automatically for the method property based on the return type of property:

type NestedProperties<T> = {
    property: () => T;
    anotherProperty: () => any;
    method: (data: ReturnType<NestedProperties<T>['property']>) => any;
};

function test<T extends Record<string, NestedProperties<any>>>(obj: T) {}

// See how it's used here
test({
    list: {
        property: () => 'string',
        anotherProperty: () => undefined,
        method: (data) => {
            // The data type will be detected as 'string'
            // Implement actions with data here
        },
    },
});

This technique could make your coding experience smoother. Good luck with your practices! :)

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

What strategies can I employ to help JSDoc/TypeScript recognize JavaScript imports?

After adding // @ts-check to my JavaScript file for JSDoc usage, I encountered errors in VS Code related to functions included with a script tag: <script src="imported-file.js"></script> To suppress these errors, I resorted to using ...

typescript create object with immutable property already set

Can you create an object literal in JavaScript and define its interface with read-only properties simultaneously? For instance let obj = { readonly prop1: 'hello', readonly prop2: 'world' } ...

Encountering the error message "Unable to access properties of null (specifically 'useState')" while trying to utilize a component from my custom library

After developing a personalized UI library and style guide to standardize components in my application, all was running smoothly until I incorporated a component utilizing the useState hook. An error consistently surfaces whenever I attempt to use a compo ...

Discovering items located within other items

I am currently attempting to search through an object array in order to find any objects that contain the specific object I am seeking. Once found, I want to assign it to a variable. The interface being used is for an array of countries, each containing i ...

Ways to create a versatile function for generating TypedArrays instances

I'm working on a function that looks like this: export function createTypedArray<T extends TypedArray>( arg : { source : T, arraySize : number } ) : T { if( arg.source instanceof Int32Array ) { return new Int32Array( arg.arraySize ); } ...

What is the best way to retrieve the value from a chosen radio button?

Here is the HTML code snippet: <ion-list radio-group [(ngModel)]="portion" (ionChange)="getPortionType()"> <ion-list-header> Select Portion </ion-list-header> <ion-item *ngFor="let item of porti ...

Utilizing JavaScript's Array.sort() method for sorting objects with varying properties

Currently, I am dealing with these specific Objects: let obj1 = { from: Date, to: Date } let obj2 = { date: Date } These Objects have been placed in an Array: let arr = [ obj1, obj2 ] My goal is to organize the objects within the array by using arr.sort( ...

Utilizing a personalized (branched) @types package

I have taken the @types/stripe package from the DefinitelyTyped repository on GitHub and created my own version in my personal GitHub repo / npm module. I understand that this custom type module may not work automatically. I attempted to integrate it by ...

Guidelines for segregating a Union from an Array

I'm currently utilizing graphql-code-generator to automatically generate TypeScript definitions from my GraphQL queries. I have a specific union within an array that I am trying to extract in TypeScript. Is this feasible? Although I came across an exa ...

The Ionic search bar will only initiate a search once the keyboard is no longer in view

In my Ionic application, I have implemented a search bar to filter and search through a list. The filtering process is triggered as soon as I start typing in the search bar. However, the updated results are not displayed on the screen until I manually hide ...

What is the best way to dynamically adjust the width of multiple divisions in Angular?

I am currently working on an angular project to create a sorting visualizer. My goal is to generate a visual representation of an array consisting of random numbers displayed as bars using divisions. Each bar's width will correspond to the value of th ...

What is the best way to utilize a single component for validating two other components?

I am encountering an issue with my components setup. I have three components in total: GalleryAddComponent, which is used to add a new element, GalleryItemComponent, used to edit an element, and FieldsComponent, the form component utilized by both GalleryA ...

Populating datasets with relative indexing

I am working on a code where I need to fill the datasets with the property isProjected set to 1. There are 3 datasets - lower estimate, projected, and upper estimate. The goal is to fill the Lower Estimate and Upper Estimate with a background color of rgba ...

The issue of Angular 9 not recognizing methods within Materialize CSS modals

I am currently working on an Angular 9 application and have integrated the materialize-css 1.0 library to incorporate a modal within my project. Everything works smoothly in terms of opening and instantiating the modal. However, I have encountered an issue ...

The essential guide to creating a top-notch design system with Material UI

Our company is currently focusing on developing our design system as a package that can be easily installed in multiple projects. While the process of building the package is successful, we are facing an issue once it is installed and something is imported ...

Discovering the worth of a variable outside of a subscription or Promise within Ionic 3

Apologies for my English. I am encountering an issue when attempting to view the results of a REST API using both subscribe and Promise methods. Within my provider, I have the following code: Provider: import { HttpClient } from '@angular/common/h ...

Managing return types in functions based on conditions

Recently, I developed a function to map links originating from a CMS. However, there are instances where the link in the CMS is optional. In such cases, I need to return null. On the other hand, when the links are mandatory, having null as a return type is ...

I'm puzzled by how my observable seems to be activating on its own without

Sorry if this is a silly question. I am looking at the following code snippet: ngOnInit(): void { let data$ = new Observable((observer: Observer<string>) => { observer.next('message 1'); }); data$.subscribe( ...

Oops! A mistake was made by passing an incorrect argument to a color function. Make sure to provide a string representation of a color as the argument next time

Encountering an issue with a button react component utilizing the opacify function from the Polished Library The styling is done using styled-components along with a theme passed through ThemeProvider. Upon testing the code, an error is thrown. Also, the ...

What is the reason this union-based type does not result in an error?

In my TypeScript project, I encountered a situation that could be simplified as follows: Let's take a look at the type Type: type Type = { a: number; } | { a: number; b: number; } | { a: number; b: number; c: number; }; I proceed to defi ...