Check the type of the indexed value

I need help with a standard interface:

interface IProps<T> {
    item: T;
    key: keyof T;
}

Is there a way to guarantee that item[key] is either a string or number so it can be used as an index for

Record<string | number, string>
?

My codebase is written in typescript v3.9.

Answer №1

If you're looking for a stricter type than keyof T, one that only allows keys with values of type string | number, then here's a solution:

type KeysAssignableTo<T, V> = {[K in keyof T]: T[K] extends V ? K : never}[keyof T]

interface IProps<T> {
    item: T;
    key: KeysAssignableTo<T, string | number>;
}

For example:

const item = {foo: 1, bar: true}

// OK
const testOK: IProps<typeof item> = {item, key: 'foo'}
// error: Type 'bar' is not assignable to type 'foo'
const testBad: IProps<typeof item> = {item, key: 'bar'}

Playground Link

Answer №2

Consider utilizing a specialized type instead of a generic one, such as:

interface CustomType {
   [key: string]: string | number;
}

Answer №3

Below is an example that resembles what you might be searching for:

interface IProps<U extends Record<string, string | number>> {
  data: U;
  identifier: keyof U;
}

type Example1 = IProps<{ num: 1 }> // valid
type Example2 = IProps<{ num: '42' }> // valid
type Example3 = IProps<{ num: ['42'] }> // invalid

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

Pass down properties to a React component

Currently, all my SVCs are created as react components and I would like the ability to pass a color attribute as a prop to override the default color of the components. However, using props attribute results in an unattractive object that needs to be defin ...

angular 2 checkbox for selecting multiple items at once

Issue I have been searching for solutions to my problem with no luck. I have a table containing multiple rows, each row having a checkbox. I am trying to implement a "select all" and "deselect all" functionality for these checkboxes. Below is an example o ...

In TypeScript, this regular expression dialect does not permit the use of category shorthand

Recently, I attempted to implement a regular expression in TypeScript: I ran the following code: const pass = /^[\pL\pM\pN_-]+$/u.test(control.value) || !control.value; To my surprise, an error occurred: "Category shorthand not allowed in ...

What is the process of invoking a service from a controller?

In my MovieSearchCtrl controller class, I have a method called returnMovies(query) that looks like this: returnMovies(query): any { return MovieSeat.MovieSearchService.getMovies(query); } Within the MovieSearchService service class, there is a functi ...

Having trouble resolving modules with Angular 2 and ASP.NET 5 (unable to locate angular2/core)?

I am diving into a fresh ASP.NET5/MVC6 project and facing some challenges along the way. Struggle 1 When I opt for classic as the moduleResolution in my tsconfig.json, I encounter an error stating: Cannot locate module 'angular2/core' Strugg ...

The art of representing objects and generating JSON responses

As I dive into building a web application using NextJS, a versatile framework for both API and user interface implementation, I find myself pondering the best practices for modeling and handling JSON responses. Key Points In my database, models are store ...

Can you explain the distinction between `any[]` and `{ [s: string]: any }`?

I was attempting to make this code snippet function properly: test(a: any[]) { let b: string[][] = []; b.push(Object.keys(a[0])); b.push(...a.map(e => Object.values(e))); } However, the compiler is throwing an error for the b.push(...a.ma ...

Executing Promises in a loop: TypeScript & Angular with IndexedDB

Currently, I am working on a data synchronization service where data is being retrieved from a web service and then stored in IndexedDB. In my TypeScript Angular Service, the code looks something like this: this.http .post(postUrl, postData) .suc ...

The error message states that the property 'registerUser' is not found on the class 'UserController'

In the controller file, I exported two functions (registerUser and loginUser) as default. No errors were thrown at that stage, but when attempting to access the routes, an error occurred stating - Property 'registerUser' does not exist on type &a ...

Utilizing various filters and sorting options on API response within Angular 8

Upon receiving the following API response: [ { "imgPaths":[ "gallery/products/55ccb60cddb4d9bded02accb26827ce4" ], "_id":"5f3e961d65c6d591ba04f3d3", "productName":" ...

When the user clicks on a specific element, ensure that it is the main focus and generate an overlay

One of my challenges is implementing a custom element that captures user input upon clicking, focusing on it and overlaying other elements. I want the overlay to disappear if the user clicks outside the div. I attempted to achieve this using the iron-over ...

Discovering how to display the hidden messages section in the absence of any ongoing chats with the help of angular2

I currently have 2 tabs set up on my page. The active messages tab is functioning perfectly without any issues. However, I am encountering an error with the closed messages tab. If there are no messages in this tab, the system displays an error message w ...

Angular 6 Material now allows for the selection of a mat-tab-link by displaying an underlining bar

My website features a mat-tab-nav-bar navigation bar, but I'm facing an issue with the mat-tab-link blue underlining bar. It doesn't move to highlight the active button, instead, it stays on the first button. However, the buttons do change into t ...

Capture and handle JavaScript errors within iframes specified with the srcDoc attribute

My current project involves creating a React component that can render any HTML/JavaScript content within an iframe using the srcDoc attribute. The challenge I am facing is implementing an error handling system to display a message instead of the iframe ...

Discovering the process of iterating through values from multiple arrays of objects and applying them to a new response in Angular 8

Received the following data from an API response: const apiResponse = { "factoryId": "A_0421", "loss": [ { "lossType": "Planned Stoppage Time", "duration": ...

Encountering an Uncaught Error: MyModule type lacks the 'ɵmod' property

I am currently working on developing a custom module to store all my UI components. It is essential that this module is compatible with Angular 10 and above. Here is the package.json file for my library: { "name": "myLibModule", &qu ...

Troubleshooting Issue: Angular 6 - Authentication token interceptor not including headers

After experimenting with various approaches using Angular 6 for the past couple of days, I recently tried implementing a solution mentioned in this post: . Despite my efforts, the header in the requests still remains unset. import {Inject, Injectable} fro ...

What is the process for overriding the module declaration for `*.svg` in Next.js?

The recent modification in Next.js (v11.0.x) has introduced new type definitions: For next-env.d.ts (regenerated at every build and not modifiable): /// <reference types="next" /> /// <reference types="next/types/global" /> ...

Issue with dispatching actions in React using TypeScript and hooks

Can you please point out what I'm doing wrong here: I am encountering the following error Type '{ wishList: any; addBookToWishList: (book: any) => void; }' is not assignable to type '{ wishList: never[]; }'. Object literal may onl ...

A method for transferring information stored in chrome.storage to a variable within an Angular component

How can I effectively assign data fetched from chrome.storage.sync.get to my Angular component's variable? Below is the code snippet of my component: export class KTableComponent implements OnInit { words: string[] = []; constructor() { } ...