Deciphering the TypeScript type in question - tips and tricks

One of my abstract classes includes a static property with various properties, where default is consistently named while the others may have random names.

  public static data = {
    default: { //only this one always have 'dafault' name
      name: 'someName',
      category: ['cat 1','cat2','catN'],
      urls: ['url1', 'url2']
    },
    property1: { //can have any random name 'property3' 'xyz'
      name: 'property1',
      category: ['cat 3','cat4','cat1'],
      urls: ['url3', 'url5']
    },
    anotherThing: { //can have any random name 'oneMoreThing' 'abc'
      name: 'anotherThing',
      category: ['cat 2','catN','cat5'],
      urls: ['url5', 'url2']
    }
  };

I am looking to enforce strict typing for this property in order to improve error validation. How would you define this structure using a TypeScript interface?

Answer №1

If you're looking to use the same name for a property and its corresponding subproperty's value, unfortunately that might not be possible...

However, if you simply want to assign names to properties, it can be done quite easily:

type MyType = {
  default: {
    name: string;
    category: string[];
    urls: string[]
  }
  [key: string]: {
    name: string;
    category: string[];
    urls: string[];
  }
};

To enhance readability or if the structure is needed elsewhere, consider adding a subtype like this:

type MySubType = {
  name: string;
  category: string[];
  urls: string[];
};

type MyType = {
  default: MySubType;
  [key: string]: MySubType;
};

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 are the two different ways to declare a property?

I am trying to update my interface as shown below interface Student{ Name: String; age: Number; } However, instead of the current structure, I would like it to be like this interface Student{ Name: String; age | DOB: Number | Date; } This means t ...

Is it possible to manually activate a dropdown event using pure JavaScript?

I am attempting to manually trigger a dropdown event using JavaScript. Below is the function where I am trying to achieve this. I have successfully halted the initial event that occurs and now I need to initiate a dropdown event. stopNavigationTriggerDrop ...

What is the method for incorporating sorting into a mat-list?

I've searched for various solutions, but none seem to work with mat-list. It's crucial for me because mat-list is the only solution where drag&drop functionality works (I always face this issue with mat-table in tables and I can't find a ...

Express is encountering an issue where it is unable to interpret the property 'name' of an undefined element coming from

I am attempting to create a fullstack application using Node.js and Angular with Material UI. I have encountered an issue while working on my web resource management application. Currently, I am facing an error during the registration and data submission ...

Managing optgroup in select dropdown using Angular 4

Is there a way to retrieve the optgroup label value within an onchange function on a select box in Angular 4? In my form, I have a select box with multiple dates as option groups and time slots in 24-hour format for booking (e.g. 1000 for 10AM, 1200 for 1 ...

Angular click switch Component keeps track of its previous state

I recently developed an Angular component that consists of a button and an icon. One key requirement is for each instance of this component to retain its own status. For example, let's say we have three instances in the app.component.html: <app-v ...

Collision Detection in Kendo UI Menu

When working with TypeScript, it ensures that the parameters are of the correct type. For Kendo's menu, in order to disable the popupCollision property, you need to set it to false. However, this property actually accepts a string as its value, so if ...

Utilizing a forwardRef component in TypeScript to handle child elements

Working with @types/react version 16.8.2 and TypeScript version 3.3.1. This forward refs example was taken directly from the React documentation with added type parameters: const FancyButton = React.forwardRef<HTMLButtonElement>((props, ref) => ...

Type of Multiple TypeScript Variables

Within my React component props, I am receiving data of the same type but with different variables. Is there a way to define all the type variables in just one line? interface IcarouselProps { img1: string img2: string img3: string img4: string ...

Having trouble retrieving spot price using Uniswap SDK due to a transaction error LOK

const quotedAmountOut = await quoterContract.callStatic.quoteExactInputSingle( immutables.token0, immutables.token1, immutables.fee, amountIn, 0 ) I set up a pool on Uniswap V3 for two ERC20 dummy tokens by using the createPool() met ...

Failure of Styling Inheritance in Angular 2 Child Components from Parent Components

My Parent Component utilizes a Child Component. I have defined the necessary styles in the Parent CSS file, and these styles change appropriately when hovering over the div. However, the Child Component does not inherit the styling classes of the Parent Co ...

Is it feasible to connect to an output component without using EventEmitter?

When it comes to creating components, I've found it quite easy to use property binding for inputs with multiple options available like input(). However, when dealing with component outputs, it can be a bit complicated as there's only one option u ...

Error encountered in spyOn TS when passing array iteration instead of a string

Instead of repeating test cases with minor adjustments, I have implemented an Array and iterated through it. However, I am encountering a TS error in test when passed from the Array instead of as a string testLink Error: No overload matches this call. ...

What steps should I take to ensure the successful function of the App Routing system in this scenario?

After creating an Angular App, I encountered a challenge in one of my services. When I call the http.post method and subscribe to it, I aim to redirect to the previous page with a parameter (e.g., "http://localhost:3000/profile/aRandomName"). Unfortunately ...

Separate the string by commas, excluding any commas that are within quotation marks - javascript

While similar questions have been asked in this forum before, my specific requirement differs slightly. Apologies if this causes any confusion. The string I am working with is as follows - myString = " "123","ABC", "ABC,DEF", "GHI" " My goal is to spli ...

What could be causing the issue with converting a Firestore timestamp to a Date object in my Angular app?

Currently, I am developing an Angular project that involves using a FireStore database. However, I have encountered a problem with the setup. Within my Firestore database, I have documents structured like the example shown in this image: The fields start ...

Efficiently incorporating multiple properties into one in Angular

Within my Angular service, I have defined variables in the following manner: export class MyService { someVariableA = 1; someParams = { someVariableB, otherVariable: this.someVariableA }; } In a component, I update 'someVariableA&a ...

problems encountered when testing azure containerclient.listblobsbyhierarchy using sinon

I have developed a REST endpoint with the code "/files/lookup", which is designed to receive a query parameter folderPath and return a list of files with details, excluding content but including metadata. The endpoint connects to Azure Blob Stora ...

What is the correct way to convert a base type value to its extended type in TypeScript?

Consider the TypeScript code block below: type URLEx = URL & { custom: string; }; const url = new URL("http://localhost:3000/foo/var"); const url_x: URLEx = { ...url, custom: "hello", }; console.log(url); // Output properti ...

Error: The reference 'GetServerSideProps' is being incorrectly used as a type instead of a value. Perhaps you intended to use 'typeof GetServerSideProps' instead?

Index.tsx import Image from 'next/image' import Head from "next/head" import { sanityClient, urlFor } from "../sanity" import Link from 'next/link' import {Collection, address} from '../typings'; import ...