Converting an array into an object by using a shared property in each element of the array as the key

I have an item that looks like this:

const obj = [
  { link: "/home", title: "Home1" },
  { link: "/about", title: "About2" },
  { link: "/contact", title: "Contact1" }
] as const

and I want to produce items in the following format:

const menu: MenuItems = {
  "/home": [{ link: "/home", title: "Home2" }] // can also include Home1, but not Contact1
}

Is it achievable to create a type for this? Here's my approach to clarify my intent:

type Obj = typeof obj;
type Item = Obj[number]

type MenuItems = {
  [K in Item["link"]]: Array<Item extends {link: K} ? Item : never>;
}

codesandbox: https://codesandbox.io/s/56564

Answer №1

Although you are on the right track, the issue lies in the fact that your T is a concrete type and not a generic type parameter. Therefore,

T extends { pointer: K } ? T : never
does not distribute over unions as expected. This means that T extends { pointer: K } will simply return false for each choice of K, resulting in never[] instead of the desired outcome.

To regain distributive conditional types, it's recommended to use a type alias similar to

type Something<X> = X extends { pointer: K } ? X : never
, and then substitute Something<T>. Fortunately, the built-in utility type Extract<T, U> already functions this way. So you can utilize the following:

type M = { [K in T["pointer"]]?: Array<Extract<T, { pointer: K }>> };

This will result in:

/* 
type M = {
    "/name"?: ({
        readonly pointer: "/name";
        readonly name: "N1";
    } | {
        readonly pointer: "/name";
        readonly name: "N2";
    })[];
    "/zip"?: {
        readonly pointer: "/zip";
        readonly name: "Z1";
    }[];
}
*/

This output aligns more closely with your expectations. Note that I made the properties optional since your constant m lacks some properties:

const m: M = {
    "/name": [{ pointer: "/name", name: "E2" }]
}; // should work

I hope this clears things up; best of luck!

Link to Playground with code

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

When converting a .ts file to a .js file using the webpack command, lengthy comments are automatically appended at the end of

As a backend developer, I recently delved into UI technologies and experimented with converting TypeScript files (.ts) to JavaScript files (.js) using the webpack command. While the conversion works well, the generated .js file includes lengthy comments at ...

How can JSON be best connected in Angular for optimal performance?

My JSON structure is as follows: { items:[], errors:[], foundItems:9 } One part of my program requires access to "items", while another part needs access to "errors." To resolve this issue, I decided to create a new interface and a new class to hand ...

Tips for including additional properties to a <button> element using ReactJS and Typescript

Currently, I am in the process of creating a unique component which consists of an ordinary <button> tag and has a new prop called aria-current. The issue at hand is that Typescript is flagging an error stating that this property does not exist with ...

Adding a method to an object with TypeScript: A step-by-step guide

In my current scenario, I am faced with a challenge where I need to test a function with a specific use of this. However, typescript poses constraints by either disallowing me from adding the method to the object, or if I define it as any, then my interfac ...

What's stopping me from using useState() to assign API data to an array?

I have a question regarding my app that makes use of the Movies API. I am making an API request and then passing the data to an array using the useState hook. Here is a snippet of my code: const App = () => { type MovieType = { rate: string, ...

Determine if a condition is met in Firebase Observable using scan() and return the

Within Firebase, I have objects for articles structured like this: articles UNIQUE_KEY title: 'Some title' validUntil: '2017-09-29T21:00:00.000Z' UNIQUE_KEY title: 'Other title' validUntil: '2017-10-29T21:00:00 ...

Updates to TypeScript 2.3.1 creating disruptions in SystemJS plunk

Check out this official Angular + TypeScript plunk using SystemJS 0.19.31, now updated to TypeScript 2.3.0. However, changing the SystemJS configuration in the same plunk to TypeScript 2.3.1 or 2.3.2 'typescript': 'npm:<a href="/cdn-cgi ...

Using ngIf to validate an empty string in Angular 5

I need assistance with validating an empty string retrieved from a server Although it is usually straightforward, it's just not working as expected <div class="ui-g-2 info-txt" *ngIf="appointment.Notes !==null || appointment.Notes !== ...

Transmit information using JSON format in Angular 8 using FormData

i am struggling with sending data to the server in a specific format: { "name":"kianoush", "userName":"kia9372", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcd7d5ddd8ce85...@example.com</a>" } H ...

Tips for expanding third-party classes in a versatile manner using Typescript

tl;dr: Seeking a better way to extend 3rd-party lib's class in JavaScript. Imagine having a library that defines a basic entity called Animal: class Animal { type: string; } Now, you want to create specific instances like a dog and a cat: const ...

What is the recommended approach for managing state in React when multiple components are trying to access and modify its data at the same time?

Issue: I am experiencing difficulty in adding new keys and/or values to the JSON editor or YAML editor when they both share and update the same state. The parent component sends JSON data to the child component through props import * as React from 'r ...

What could be preventing my state from changing to false when I click the close button on the menu?

Despite initializing my state to false, the problem arises when I open and close my menu. The state never actually becomes false, causing the closing animation of the NavBar to not run as expected. The component: import CloseButton from "./CloseButto ...

Is it possible for Angular2 to map a lone JSON object?

Dealing with a JSON response that is a single object, rather than an array, can be tricky. Recently in my project, I encountered a situation where I needed to map and use such a response from an API to fill out a template. It seemed like a simple task at f ...

Issue: The TypeError reported is due to the absence of any definition for "_co.category.category_type"

I have two models: CategoryTypes and Categories. Each category type contains multiple categories. These are my two models. Categories Model import { Categories } from '../../categories/Mode/Categories' export class CategoryType { _id: strin ...

The language in the React Native app remains unchanged despite utilizing i18next.changeLanguage

I am currently attempting to integrate the i18next library into my React Native app in order to facilitate language changes, but I have encountered difficulties with translation. image description here I have created an i18n.tsx file. import i18next from & ...

I am in need of assistance with incorporating a particular hibernate Inheritance mapping into my project

I am dealing with a situation where I have two classes, parent and child, with a self-referential relationship on the child side. The database is set up with separate tables for both parent and child, sharing the same "id", and using the column "holder" as ...

Error: It is not possible to assign a value to the Request property of the Object since it only has a getter method

Encountering issues while attempting to deploy my Typescript Next.js application on Vercel. The build process fails despite functioning correctly and building without errors locally. Uncertain about the root cause of the error or how to resolve it. The f ...

How to retrieve a variable from an object within an array using AngularJS code

I recently started learning TypeScript and AngularJS, and I've created a new class like the following: [*.ts] export class Test{ test: string; constructor(foo: string){ this.test = foo; } } Now, I want to create multiple in ...

WebStorm displays all imported items as unused in a TypeScript backend project

https://i.stack.imgur.com/J0yZw.png It appears that the image does not display correctly for files with a .ts extension. Additionally, in .tsx files, it still does not work. In other projects using WebStorm, everything works fine, but those projects are o ...

The rapid execution of code causing an observable race condition

When exporting a CSV file in my code, I encounter a race condition while trying to modify some data before the export. The issue is that the id gets set correctly, but the number only updates after the method is called a second time. I believe the proble ...