What is the correct way to fetch all attributes of a particular key type from an interface using TypeScript?

Exploring arrays, I discovered the following setup:

const MyArray = [
  { name: "Alice", age: 15 },
  { name: "Bob", age: 23 },
  { name: "Eve", age: 38 },
];
 
type Person = typeof MyArray[number];

Curious, I attempted a similar approach with interfaces:

interface A {
  a: number;
}

type PropertiesTypeByString = A[string]

Unfortunately, an error was thrown:

Type 'A' has no matching index signature for type 'string'.

If I want to access all properties of type string, what is the best way to tackle this issue?

Answer №1

If you wish to access an object type A by indexing, the key must be compatible with keyof A (using the keyof type operator). Since A does not have a string index signature, you cannot use A[string]. Instead, you can merge keyof A with string to obtain "all the keys of A that are of type string:

const sym = Symbol();
interface A {
  a: number;
  b: boolean;
  3: Date; // numeric key, not string
  [sym]: Element // symbol key, not string
}

type StringPropertiesType  = A[keyof A & string];
//   ^? type PropertiesTypeByString  = number | boolean

Link to playground with code

Answer №2

You have the ability to remove keys from an object that do not match a specific type (e.g. string) using a technique called Mapped Type and Key Mapping. If a key K is a string, it remains in the object; otherwise, it is remapped to never.

interface A {
  a: number;
  1: string;
}

type KeysOfType<T, U extends PropertyKey> = keyof {
  [K in keyof T as K extends U ? K : never]: T[K];
};
type Result = KeysOfType<A, string>;
//   ^? type Result = "a"

TypeScript Playground


In relation to the question at hand, it's important to note that typeof MyArray[number] doesn't pertain specifically to keys of type number. The concept of indexing with number simply implies that all items in the array can be accessed in the same manner. Instead of specifying typeof MyArray[0] or typeof MyArray[1], you can generalize by using number.

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

Challenges with implementing asynchronous functions in NestJS controllers

Currently, I am in the process of developing a finance tracker application that involves importing data from a CSV file. The import functionality checks if an entry already exists in the database, adds a specific category to it if not found, and then saves ...

Generate random entries from an object based on specific criteria and append them to a fresh object using Typescript

Experimenting with Ionic2 and Typescript has been my recent focus. I have an object that contains various meals, calorie counts, and meal types (such as vegan). This is how the object looks: [ { "id":14093, "name":"Proteinshake mit Wasser ...

Is there a way to extract various pieces of data from a single object and implement them in a NextJs 13 application directory?

My Django RESTapi is providing output data in the following format: { "count": 1000, "next": "http://127.0.0.1:8000/store/products/?page=2", "previous": null, "results": [ { "id": 648, ...

Encountering "Module ts-jest not found in the transform option" Error During Bazel Testing

In my working Bazel BUILD file, I have set up the following configurations: package(default_visibility = ["//visibility:public"]) load("@io_bazel_rules_docker//nodejs:image.bzl", "nodejs_image") load("@npm_bazel_typescript//:index.bzl", "ts_library") # ...

Adding Crypto-JS to an Angular 2 application

For my Angular 2 development using TypeScript and SystemJS, I needed to integrate crypto-js. Here is the configuration in my systemjs.config.js file: (function (global) { System.config({ paths: { 'npm:': 'node_modules/' ...

Enhancing Subscription Collection with Angular and RX Framework

Exciting Update! After successfully finding the solution, I created a handy ng2-rx-collector tool inspired by the accepted answer to simplify the process even further. It's designed to assist anyone who might encounter similar challenges in the futur ...

Display the list of cities associated with the country chosen in the form

I am currently working with the repository found at https://github.com/country-regions/country-region-data/blob/master/data.js to create a mapping of countries and their related cities. I'm seeking guidance on how to achieve this task effectively. My ...

Manipulating arrays of objects using JavaScript

I am working with an array of objects represented as follows. data: [ {col: ['amb', 1, 2],} , {col: ['bfg', 3, 4], },] My goal is to transform this data into an array of arrays like the one shown below. [ [{a: 'amb',b: [1], c ...

Adding corresponding classes to the body element based on the selected radio button in Angular 6

Is there a way to dynamically add a class to the body tag and the parent element when clicking on radio buttons? For example, consider the following code snippet: <form action=""> <input type="radio" value="layout1">Layout 1<br> <i ...

What is the Angular2 equivalent of the AngularJS $routeChangeStart event?

During our time working with AngularJS, we utilized the $routeChangeStart/End event in the $rootScope to monitor changes in the route object. What is the equivalent method for monitoring route changes in Angular2? How can we achieve the same functionality ...

Issues with the functionality of Angular Firebase Authentication Service

I am currently working on setting up an authentication service in Angular that will integrate with Google Firebase for a Login form. However, I have encountered an issue where including the service in the constructor of my LoginComponent prevents me from a ...

"Import data from a text file and store it as an array of objects using Types

I need assistance with converting the information in my text file into an array of objects. Below is a snippet of the data from the text file: DOCNO NETAMOUNT IREF1 IREF2 DOCDT 001 30000 50 100 6/7/2020 2 40000 40 90 6/7/2020 Currently, t ...

Retrieve data from TypeScript file (.ts) and use it in an HTML document

Recently I started learning Typescript and HTML as I work on building an Angular2 application. At the moment, I have a TypeScript file that resembles the following structure: import {Http, Headers} from 'angular2/http'; import {Component} from & ...

What could be causing the strange output from my filtered Object.values() function?

In my Vue3 component, I created a feature to showcase data using chips. The input is an Object with keys as indexes and values containing the element to be displayed. Here is the complete code documentation: <template> <div class="row" ...

Exploring the versatility of string types in TypeScript

I'm currently working in React and have an array of pages set up like this. export const pages: Page[] = [ { path: "/", exact: true, component: PageHome }, { path: "/home2", exact: true, component: PageHome2 }, { path: " ...

Is it possible to retrieve all mandatory attributes of a TypeScript object?

Is there a method or approach available that can retrieve all necessary properties from a TypeScript interface or an object? For instance, something along the lines of Object.getOwnPropertyDescriptors(myObject) or keyof T, but with the specific details o ...

Develop a simulated version that does not include all the functionalities of the primary service

Let's imagine a scenario where there is an OriginalService class with various methods class OriginalService { method1() { } method2() { } method3() { } .. } Now, suppose we need to create a mock of OriginalService that will only be used with ...

Apply a spread of nested elements onto another spread

I am working with an array containing last names of Persons and need to populate new entries. However, I only have the last names and not the full Person objects. How can I address this issue? type Person = { name: string, lastName: string, age: ...

What is a way to conceal an Angular Material FormGroup on the webpage until the data has been retrieved from the background?

I am working on a simple webpage that includes a form group with multiple controls. In my ngOnInit method, I am sending a get request to fetch data from the server. While waiting for this data to load, I want to hide the form and only display it once the d ...

Navigating from a Card to a new View in Angular

I am currently developing a project using Angular (latest version). Within my application, I have the functionality to dynamically generate bootstrap cards from an Order Array and display them in my "Order-Item-Component through its respective template. ...