What is the method for deducing the names that have been announced in a related array attribute

In my definitions, I have identified two distinct groups: Tabs and Sections. A section is encompassed by tabs (tabs contain sections).

When defining sections, I want the tab names to be automatically populated by the previously declared sibling tabs.

But how can I determine the names of siblings? Here's what I experimented with (Give it a try on our platform):

export type TabDeclaration<TabName extends string = string> = {
  name?: TabName;
};

export type SectionDeclaration<
  Tabs extends TabDeclaration[],
  SectionName extends string = string
> = Tabs extends TabDeclaration<infer TabName>[]
  ? {
      name?: SectionName;
      tab?: TabName;
    }
  : never;

type TabsAndSections<Tabs extends TabDeclaration[] = TabDeclaration[]> = {
  tabs: Tabs;
  sections: SectionDeclaration<Tabs>[];
};

var tabsAndSections: TabsAndSections = {
  tabs: [
    {
      name: 'Tab 1'
    },
    {
      name: 'Tab 2'
    }
  ],
  sections: [
    {
      name: 'Section 1',
      tab: '' /* <---- Should autocomplete "Tab 1" or "Tab 2" */
    }
  ]
}

tab: should automatically suggest "Tab 1" or "Tab 2".

Answer №1

A useful approach is to develop a function that assists in identifying valid tab names based on the provided values.

The restriction placed on the second type parameter L implies that the tab names within the sections must be chosen from the available tabs.

Playground

type Section<K extends string> = {
  name?: string;
  tab?: K;
}

type Tab<K extends string> = {
  name: K;
};

type TabsAndSections<K extends string, L extends K> = {
  tabs: Array<Tab<K>>,
  sections: Array<Section<L>>;
};

const asTabsAndSections = <K extends string, L extends K>(
  obj: TabsAndSections<K, L>
): TabsAndSections<K, L> => obj;

const tabsAndSections = asTabsAndSections({
  tabs: [
    {
      name: 'Tab 1'
    },
    {
      name: 'Tab 2'
    }
  ],
  sections: [
    {
      name: 'Section 1',
      tab: 'Tab 1' /* <---- Should autocomplete "Tab 1" or "Tab 2" */
    }
  ]
})

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 steps are involved in setting up a sorting feature?

In order to utilize the array.sort() function, a number-returning function must be specified. Typically, it would look something like this: myArray.sort((item1, item2) => a < b); However, I am aiming for a different structure: myArray.sort(by(obj ...

What should be the datatype of props in a TypeScript functional HOC?

My expertise lies in creating functional HOCs to seamlessly integrate queries into components, catering to both functional and class-based components. Here is the code snippet I recently developed: const LISTS_QUERY = gql` query List { list { ...

After upgrading to version 8 of the Firebase JS SDK, the "firestore" module (imported as "firebase") could not be located within the "firebase" package

After upgrading the firebase JS SDK from v7 to v8.0.0, I changed my import of firebase as shown below. import * as firebase from 'firebase'; However, attempting to access certain properties resulted in an error message: firebase.firestore.FieldV ...

Is there a way to use Regex to strip the Authorization header from the logging output

After a recent discovery, I have come to realize that we are inadvertently logging the Authorization headers in our production log drain. Here is an example of what the output looks like: {"response":{"status":"rejected",&quo ...

Showing nested routes component information - Angular

I am working on a project that includes the following components: TodosComponent (path: './todos/'): displaying <p>TODO WORKS</p> AddTodosComponent (path: './todos/add'): showing <p>ADD TODO WORKS</p> DeleteTo ...

The Angular 6 View does not reflect changes made to a variable inside a subscribe block

Why isn't the view reflecting changes when a variable is updated within a subscribe function? Here's my code snippet: example.component.ts testVariable: string; ngOnInit() { this.testVariable = 'foo'; this.someService.someO ...

What is the equivalent of getElementById in .ts when working with tags in .js?

Looking to incorporate Electron, Preload, Renderer with ReactJS and TypeScript into my project. <index.html> <body> <div id="root" /> <script src='./renderer.js'/> </body> <index.ts> const root = Re ...

How to convert typescript path aliases into relative paths for NPM deployment?

I am currently working on a typescript project that utilizes paths for imports. For instance: "paths": { "@example/*": ["./src/*"], } This allows the project to import files directly using statements like: import { foo } from "@example/boo/foo"; Whe ...

Clearing the require cache in Node.js using TypeScript

I need to repeatedly require a module in TypeScript and Node for testing purposes. I came across an approach on this post which suggests the following code snippet: const config = require('./foo'); delete require.cache[require.resolve('./fo ...

The property 'enabled' is not a standard feature of the 'Node' type

Within the code snippet below, we have a definition for a type called Node: export type Node<T> = T extends ITreeNode ? T : never; export interface ITreeNode extends TreeNodeBase<ITreeNode> { enabled: boolean; } export abstract class Tre ...

What is the best way to verify the type of an object received from request.body in Typescript

Is it possible to check the object type from the request body and then execute the appropriate function based on this type? I have attempted to do so in the following manner: export interface SomeBodyType { id: string, name: string, [etc....] } ...

Solve the issue of the __typename union

Imagine having the following union: export type IBookmarkItemFragment = | ({ __typename: "Story" } & { story: number; }) | ({ __typename: "Product" } & { product: number; }) | ({ __typename: "Project" } & { proj ...

Combining results from multiple subscriptions in RxJS leads to a TypeScript compiler error

I am utilizing an Angular service that provides a filterObservable. To combine multiple calls, I am using Rx.Observable.zip(). Although it functions as expected, my TypeScript compiler is throwing an error for the method: error TS2346: Supplied paramete ...

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 ...

Error: Attempting to access properties of an undefined value while retrieving data from Firebase

Struggling with displaying data in my NextJS app. Data is being fetched from Firebase, and the interface structure is as follows: export default interface IUser { name: string; email: string; uid: string; profileImageURL: string; publicData: { ...

A guide to configuring VSCode to recognize the DefinitelyTyped global variable (grecaptcha) within a Vuejs 3 TypeScript project

I have recently set up a new project using Vue.js 3 and TypeScript by running the command npm init vue@latest. I now want to integrate reCaptcha v2 into the project from scratch, without relying on pre-existing libraries like vue3-recaptcha-v2. Instead of ...

When employing GraphQL Apollo refetch with React, the update will extend to various other components as well

My current setup involves using react along with Apollo. I have implemented refetch in the ProgressBar component, which updates every 3 seconds. Interestingly, another component named MemoBox also utilizes refetch to update the screen at the same int ...

What is the best way to detect object changes in typescript?

Having an object and the desire to listen for changes in order to execute certain actions, my initial approach in ES6 would have been: let members = {}; let targetProxy = new Proxy(members, { set: function (members, key, value) { console.log(k ...

The statement "import React from 'react'" is automatically removed by VS Code

When I need to remove unused modules that I no longer need, I frequently use shift + alt + o. This method has worked perfectly for me in the past when editing .tsx files. However, recently, VS Code seems to be removing the import React from 'react&ap ...

Events bound to JSX elements created in an array map are not being triggered by React

My current task involves working on a compact react + typescript (1.6) application designed for editing slideshows. The functionality of the app is straightforward. A sidebar on the left displays all existing slides, and upon clicking, a canvas appears on ...