Exploring index type signatures in TypeScript

I'm relatively new to using TypeScript and I am trying to define a type similar to the following:

type U = { [key: string]: number }; // any string for the keys
type T = { [key: string]: U };      // again, any string for the keys

Here's an example of how it would be used:

const test: T = {
    'aaa': {
        'xxx': 777,
        'yyy': 888,
        'zzz': 999  // expecting an error here
    },
    'bbb': {
        'xxx': 444,
        'yyy': 555,
        'ooo': 666  // expecting an error here
    }
};

Is there a more sophisticated signature that can ensure all properties of U within T will have the same keys?

Answer №1

To mandate specific keys within an interface, you can utilize an index signature:

interface CustomInterface { 
  [key: string]: number;
  xxx: number;
  yyy: number;
  zzz: number; 
}; 

If the goal is to ensure two objects share the exact same keys, you can achieve this using generics:

interface BaseDataType<T> {
  xxx: T;
  yyy: T;
  zzz: T; 
}

type PrimaryType = BaseDataType<number>;
type SecondaryType = BaseDataType<PrimaryType>;

Answer №2

Specify U with specific attributes to achieve the desired functionality:

type U = {
    "xxx": number,
    "yyy": number;
    "zzz": number;
}
type T = { [key: string]: U }

This approach helps catch errors like ooo:

const test: T = {
    'aaa': {
        'xxx': 777,
        'yyy': 888,
        'zzz': 999
    },
    'bbb': {
        'xxx': 444,
        'yyy': 555,
        'ooo': 666  // error expected here
    }
};

You can experiment on the Playground using this link for a complete example.

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

Establish a route nickname for files outside the project directory

I'm currently tackling a project that is divided into multiple angular projects. Within these projects, there are some services that are shared. Is there a way for me to incorporate these services into my project without encountering errors? /root / ...

Using TypeScript, you can utilize RxJS to generate a fresh Observable named "Array" from a static array

I've successfully created an observable from an array, but the issue is that its type shows as Observable<number> instead of Observable<number[]> getUsers(ids: string[]): Observable<number[]> { const arraySource = Observable.from ...

Loop through the coefficients of a polynomial created from a string using JavaScript

Summary: Seeking a method to generate a polynomial from specified coordinates, enabling coefficient iteration and optional point evaluation I am currently developing a basic JavaScript/TypeScript algorithm for KZG commitments, which involves multiplying c ...

Angular error: Trying to assign a value of type ArrayBuffer to a string type

Is there a way to display a preview of a selected image before uploading it to the server? Here is an example in HTML: <div id="drop_zone" (drop)="dropHandler($event)" (dragover)="onDragover($event)"> <p>drag one or more files to ...

How can we declare and showcase a generic object with an unspecified number and names of keys in React using TypeScript?

I am facing a challenge with objects that have a 'comments' field. While all the other fields in these different objects have the same types, the 'comment' field varies. I do not know the exact number or names of the keys that will be p ...

The Angular application is not functioning properly after running npm start, even though all the necessary packages have

Encountering a perplexing issue with my Angular application. After checking out the code on my new machine, I attempted to run my existing Angular 12 project. However, despite the application running properly in the command prompt, it is not functioning as ...

What is the correct way to initialize an object in Angular 5?

I am in the process of developing a dynamic questionnaire service that utilizes a dynamic form approach. The structure consists of a question base followed by various types of questions such as textboxes, dropdowns, etc. My next step was to create a quest ...

Exploring the power of TypeScript with React-Router

Struggling to set up react-router with typescript. I've installed @types/react-router, but encountering an error message saying: @types/react-router/index"' has no exported member 'hashHistory' I've experimented with different ro ...

Middleware fails to execute on routing in Nextjs 13.4 application

Something's not quite right. I can't seem to get my middleware to run... Here's the code I'm using: export const config = { matcher: '/api/:function*', }; I specified this config so that it would run only when there's ...

What could be causing the parameter "id" to be undefined in Nest JS

Exploring the layout of the project directory, I am currently utilizing yarn berry for the monorepo setup with two distinct packages. The first package houses all the applications, while the second one contains shared libraries and modules. `- apps bff ...

Troubleshooting the issue with mocking the useTranslation function for i18n in JEST

Currently, I am facing an issue with my react component that utilizes translations from i18next. Despite trying to create tests for it using JEST, nothing seems to be getting translated. I attempted to mock the useTranslation function as shown below: cons ...

What could be causing this error when running nodemon in an Angular TS file?

One issue I am facing is that upon running the npm run dev command, I encounter the error message stating that 'node_modules is not recognized as an internal or external command'. Here is an image showing the specific error: https://i.sstatic.ne ...

The Word Document is unable to locate the module or its associated type declarations

Encountering an issue while attempting to import a file from the src/assets/documents directory. https://i.sstatic.net/Gxq05.png Currently working on a React Project using Typescript. The goal is to import a file and use its value within an anchor tag fo ...

A guide on activating the <b-overlay> component when a child triggers an Axios request in vue.js

Is there a way to automatically activate the Bootstrap-vue overlay when any child element makes a request, such as using axios? I am looking for a solution that will trigger the overlay without manual intervention. <b-overlay> <child> ...

Help! I keep getting the NullInjectorError in the console saying there is no provider for Subscription. Why is this happening?

Here is the code snippet I'm working on within a component: import { Component, OnDestroy, OnInit } from '@angular/core'; import { interval, Subscription } from 'rxjs'; @Component({ selector: 'app-home', templateUrl ...

Adjust the dimensions of the mat-icon-button

Is there a way to adjust the size of a mat-icon-button? Currently, my icon is set at 24px and I would like to increase it to 48px. I am using mat-icon as the button content, but it seems that mat-icon-button has a fixed size of 40px by 40px. <button ...

Guide on integrating react-tether with react-dom createPortal for custom styling of tethered components based on their target components

Within a Component, I am rendering buttons each with its own tooltip. The challenge is to make the tooltip appear upon hovering over the button since the tooltip may contain more than just text and cannot be solely created with CSS. The solution involves ...

Top method for extracting a correlation matrix using an API endpoint

I am currently storing correlations on Google Firebase in a structure that resembles the following: {a: {a: 1.0, b: 0.6, c: -0.3, ...}, b: {a: 0.6, b: 1.0, c: -0.5, ...}, ...} My goal is to efficiently retrieve a complete correlation matrix while also hav ...

Adding a custom type to a selected option for the onChange event in React-Select can be done by modifying the

After creating a SelectBox component using react-select and applying onChange event to it, I encountered an issue. I wanted to include a type "SelectedItemType" to the selected option in the onChange event, but the property of onChange was defined as (prop ...

Tips for updating the front end with the status of a lengthy playwright test

In the node backend, I have defined a route for test progress using SSE (https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events). The URL initialization is happening on the frontend. Below is the code snippet from th ...