What is the method in TypeScript for defining a property in an interface based on the keys of another property that has an unknown structure?

I recently utilized a module that had the capability to perform a certain task

function print(obj, key) {
  console.log(obj[key])
}

print({'test': 'content'}, '/* vs code will show code recommendation when typing */')

I am eager to implement this feature in my project, but unfortunately, I cannot remember the name of the module and I am uncertain if my memory serves me right (perhaps it's not even possible).

Currently, I am developing a package and have written some code like this:

interface Box {
  content: {
    [key: string]: string
  }
  using: string // key of content 
}

const box: Box = {
  content: {
    'something': 'inside'
  },
  using: 'something'
}

function showBox(box: Box) {
  console.log(box.content[box.using])
}

The content object actually originates from another package using Typescript. Ideally, I would prefer not to encapsulate the type.

In order to aid developers in identifying bugs while coding, I am investigating whether there is a method to validate an invalid Box type like so:

const box: Box = {
  content: {
    'something': 'inside'
  },
  using: 'samething' // trigger an error during type checking
}

Alternatively, I am searching for any approach that can enable IDEs to provide code recommendations indicating that using should be a key within the content object.

At present, my code appears as follows, but it does not align with my desired outcome, and I am stuck on how to proceed further

interface Box {
  content: {
    [key: string]: string
  }
  using: keyof Box['content'] // will result in string | number
}

A big thank you to everyone who responds!

Answer â„–1

Your solution appears to be correct, however the IDE is not able to provide suggestions because keyof Box['content'] is defined as an arbitrary string. If you have specific requirements for the structure of content, you can define it within the Box interface like this:

interface Box {
  content: {
    something: string;
  };
  // now it only allowed to be 'something', and IDE will suggest it
  using: keyof Box['content'];
}

If the type of your content is actually a parameter (meaning it can vary for different types), you should make it a parameter of the Box interface by creating a generic interface like this:

interface GenericBox<T> {
    content: T;
    using: keyof T;
}

You can then use it in the following way:

// Example interface to fill a box
interface TestContent {
    x: string;
    y: number;
}

const genericBox: GenericBox<TestContent> = {
    content: {x: '', y: 0},
    using: 'x', // now it can be only 'x' or 'y', and IDE will suggest it
};

You can try out this concept on the 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

Error in TypeScript when accessing object using string variable as index

Currently, I am facing a challenge in my project where I am dynamically generating routes and managing them in an Elysia(~Express) application. The issue arises when TypeScript's type checking system fails to index an object using a string variable. S ...

Experimenting with error boundaries by utilizing the React Testing Library and Jest:

I am facing an issue while writing a test for my error boundary higher-order component (HOC). The problem arises when I mock throwing an error in my wrapped component, causing the test to fail because it recognizes the error as a genuine one instead of und ...

Unexpected behavior observed in ng-select when pasting search values

When attempting to update an array of strings acting as the model for an ng-select, the values do not appear correctly in the search box. https://i.sstatic.net/WqdJ6.png The values that are displaying correctly are the ones selected from the dropdown men ...

Diverse Selection of Font Awesome Icons

In my React project with TypeScript, I have a header component that accepts an Icon name as prop and then renders it. I am trying to figure out the best way to ensure that the icon prop type matches one of the existing FontAwesome Icons. import { FontAwe ...

When package.json is imported, files are not compressed

Currently, I am working on developing a cli package and when it comes to displaying the version, I am utilizing the version imported from package.json. Upon running tsc, the structure of the dist folder appears as follows: /dist --/package.json --/README. ...

The function to increase the number of days on a date in Angular is experiencing technical issues

I'm facing an issue where I need to add 12 days to a specific date, but the new date is not coming out as expected. Below is the code snippet: addDays(days: number): any { let startDate = new Date(this.selectedDeliveryDate); let endDate = new ...

Angular 7 ERROR: The SystemJS reference is missing

In the process of developing an Angular 7 project with systemjs for dynamic module loading, I encountered an issue. Upon attempting to utilize it, I encountered the following error: ERROR ReferenceError: SystemJS is not defined Within my package.json f ...

The specified type cannot be assigned to the type 'IntrinsicAttributes & MoralisProviderProps'

I'm brand new to TypeScript and I have a question about setting initializeOnMount to true. Why does it only allow me to set it to false? Here is the error message: Type '{ children: Element; appId: string | undefined; serverUrl: string | undefine ...

Changing the ngModel value within ngFor loop

I am working on a project where I need to display a list of grades from an object called 'grades'. Additionally, I want to integrate a slider component for each grade, with the value of the slider corresponding to a predefined list. However, it s ...

There was an error encountered trying to access the options (URL) with a 405 method not allowed status. Additionally, the request to load the (URL) failed with a response indicating an

I attempted to retrieve data from an API using httpClient in Angular 5, but encountered errors. Below are the issues I faced: 1) ERROR: when trying to access http://localhost:8080/api/getdata, I received a 405 error (method not allowed). 2) ERROR: failed t ...

I'm having trouble with one of my filter pipes not displaying any results. Can anyone help me troub

I have recently included a new filter for DL, but it seems that the results are not showing up as expected. Any ideas on what changes I should implement? <div class="form-group float-left mr-4"> <strong>DL</strong> <br /> ...

The issue of resolving custom paths imports in Typescript has been a persistent challenge for developers

Currently, I am developing a project in PHP and utilizing Typescript. I aim to follow a monorepo pattern similar to what NX offers. However, I am facing challenges when attempting to compile typescript for each of my apps. Here is the current structure of ...

Utilizing nested services for enhanced functionality

I'm facing an issue with my folder structure: . ├── lib/ │ └── dma/ │ ├── modules/ │ │ └── cmts/ │ │ ├── cmts.module.ts │ │ └── cmts.service.ts │ └┠...

Guide on invoking child components' functions from the parent component in Angular 6

Main Component import { Component } from '@angular/core'; import { DisplayComponent } from './display.component'; @Component({ selector: 'my-app', template: ` <button (click)="submit()">Call Child Com ...

Limit the type to be used for a particular object key in TypeScript

My pet categories consist of 'dog' and 'cat' as defined in the Pet type: type Pet = 'dog' | 'cat' I also have distinct types for allowed names for dogs and cats: type DogName = 'Jack' | 'Fenton&apos ...

Exporting from Excel is causing dates and times to be displayed as numbers instead

Having trouble with a specific date while exporting an Excel file. Refer to the screenshot of the Excel file for clarity: https://i.stack.imgur.com/7mFE4.png The date '01/02/2019 00:00:00' is being treated as a number instead of displaying corre ...

What is the best way to handle .jsx files in my library bundling process with Rollup?

Currently, I am in the process of developing a component library using storybook and rollup. Here is the configuration file rollup.config.mjs /* eslint-disable import/no-extraneous-dependencies */ import peerDepsExternal from 'rollup-plugin-peer-deps- ...

What are the reasons for deprecating bindToController in Typescript?

When I am creating an AngularJS directive using TypeScript, I typically use the bindToController property to bind parameters to the controller for easy access. export class MyDirective implements IDirective { controller = MyController; controllerA ...

NGRX reducer avoids generating errors due to incorrect assignments

My experience with ngrx is relatively new. In my typical TypeScript work, I usually encounter an incorrect assignment error like the one below due to a missing property in the interface declaration: interface IExample { count: number; } let initialState ...

Checkbox: Customize the appearance of the root element

I am trying to modify the root styles of a Checkbox component, but it is not working as expected. Here is my code: <CheckboxItem onChange={()} checked={isChecked} label="Show Checkb ...