Slim and tightly nested `Record` structure

Our configurations require server-side data in this format

const permissionOptions = [
  'read:workspace',
  'create:bot',
  'create:invitation',
  'delete:bot',
] as const

The objective is to simplify this data into a Result object like the following

type Result = {
    read: {
        workspace: Boolean
    },
    create: {
        bot: Boolean,
        invitation: Boolean,
    },
    delete: {
        bot: Boolean
    }
}

This is our progress so far (playground)


type PermissionString = typeof permissionOptions[number]
type UnionActions<T extends string> = T extends `${infer Action}:${string}` ? Action : never
type UnionKeys<A extends PossibleActions, T extends string> = T extends `${A}:${infer Key}` ? Key : never

type PossibleActions = UnionActions<PermissionString>
type PossibleKeys = UnionKeys<PossibleActions, PermissionString>

type Result = Record<PossibleActions, Record<PossibleKeys, boolean>>

function test(r: Result): void {
    r.read.bot // read should only have `workspace`
    r.create.workspace // create should only have 'bot' | 'invitation'
}

Answer №1

Found the solution with help from mapped types

type Solution = {[A in PossibleActions]: Record<UnionKeys<A, PossibleKeys>, Boolean>}

(playground)

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

A comprehensive guide on constructing a literal object in Typescript by combining an array with an object

Recently, I came across this Typescript code snippet: type SortedList = T[] & {_brand: "sorted" }; function binarySearch<T>(xs: SortedList<T>, x: T): boolean let low = 0; let high = xs.length - 1; while (high ...

Troubleshooting issue with Angular 11 and .Net post method malfunctioning

When attempting to send data from Angular to .Net, I am encountering an issue where the breakpoint in the Controller C# is not being hit. Do I need to make any additional configurations? Previously, I have successfully sent data in this manner in Angular 8 ...

The outcome of a promise is an undefined value

I am facing an issue where I need to access the result of my API call outside the promise, but the value I receive is always undefined. Within the OrderService : public async getOrderPrice(device: string) : Promise<any> { this.urlOrderPrice = th ...

What is a simple way to exclude a prop from a declaration in a React/TypeScript project in order to pass it as undefined

I'm trying to accomplish this task but encountering a typescript error indicating that the label is missing. Interestingly, when I explicitly set it as undefined, the error disappears, as shown in the image. Here's how my interface is structured ...

Troubleshooting NodeJS Azure function within a docker container using VS Code debugger

I am facing issues setting up remote debugging for my NodeJS Azure function in a docker container. Configuration: Following the guidelines from official documentation, I created an HTTP triggered function as per the steps below: func init --worker-runtim ...

Issues arise when attempting to assign GraphQL types, generics, and NestJS Type<> as they are not interchangeable with Type<&

I've been attempting to use this definition: import { GraphQLScalarType } from 'graphql'; import { Type } from '@nestjs/common'; export function createFilterClass<T extends typeof GraphQLScalarType>( FilterType: Type&l ...

Decorators: A Handy Tool for Renaming Instance Keys

I have a scenario where I have a class defined as follows: class A { description: string } My requirement is that when creating an instance of this class, I want to set the description attribute. However, when accessing the instance of the class, I woul ...

Resolving NestJS Custom Startup Dependencies

In my setup, I have a factory responsible for resolving redis connections: import {RedisClient} from "redis"; export const RedisProvider = { provide: 'RedisToken', useFactory: async () => { return new Promise((resolve, reject ...

What steps are required to generate dist/app.js from a script file in my TypeScript project?

I am currently working on a project using node, express, and TypeScript. When I run npm run build, everything builds without any issues. However, when I attempt to run npm run start, I encounter the following error: @ruler-mobility/[email protected] /User ...

Validating a field conditionally upon submission

Adding a required validation conditionally to the "imageString" field upon submission, but the expected required validation is not being set. Initializing the form. constructor(){ this.poeForm = this.fb.group({ imageString: [""], imageFileNam ...

It is feasible to completely override a class in TypeScript

I have a subclass defined as follows: customException.ts /** * Custom Error class. * * @class Error * @extends {Error} */ class Error { /** * @type {string} * @memberof Error */ message: string; /** * @type {boolean} * @memberof ...

Issue encountered with TypeORM and MySQL: Unable to delete or update a parent row due to a foreign key constraint failure

I have established an entity relationship between comments and posts with a _many-to-one_ connection. The technologies I am utilizing are typeorm and typegraphql Below is my post entity: @ObjectType() @Entity() export class Post extends BaseEntity { con ...

Adjust property value based on changes in a related property

Currently, I am developing a TypeScript-powered Angular (5) application and I have encountered a puzzling question that is proving elusive to solve. Let me illustrate with the following example: ... export class SomeComponent implements onInit { ... ...

mat-table dataSource is not functioning properly with REST API integration

I'm facing an issue while trying to populate a Material Table with data. My model Block has fields such as id, date, etc. The API call is made in data.service and the function getAllBlock() fetches the blocks. I tested this in the app.component.html ...

Encountering "Error: Class constructor vA cannot be invoked without 'new'" when using Angular 10 Kendo Grid

I am currently working on integrating a Kendo Grid into my Angular application. However, I have run into an error when enabling the Kendo Grid component: vendor.4add67dadae0cd9152b9.js:16 ERROR Error: Uncaught (in promise): TypeError: Class constructor vA ...

Establishing limitations on the type of a value while preserving its specific type in TypeScript

Is there a way to declare a value that extends a specific type and maintains its narrow type without the need to call a function? const stringRecord : <T extends Record<string, string>>(x: T)=>T= (x) => x; //Define value that extends Re ...

Measuring the frequency of using useContext in React and Typescript

I'm diving into the world of the useContext hook to enhance my understanding. Experimenting with this codesandbox, I've set up a functionality where items from the left component can be added to the right. Now, my goal is to track how many times ...

Error: The value associated with the key 'services.authentication.basic.user.service' is not defined in the current context, causing a ResolutionError with a code of

I have been working on creating custom authentication using LoopBack 4. I referred to the following documentation: services.authentication.basic.user.service is showing as not bound. This pertains to the user.controller where I've injected JWTAuthen ...

Obtaining an OBJECT from a hashmap instead of a string

In my code, I am working with a hashmap and I want to extract all the values from this map without needing to reference a specific key. Here is a basic overview of the process: Create a hashmap using an external file with a structure of "id:value" Utili ...

A guide on implementing Redux Toolkit in an SPFX (typescript) project

I am currently working on developing SPFX components using typescript and webpack. My goal is to integrate redux toolkit into my project, but it is causing compilation errors. Here is what I have done so far: Created the project structure using yo Insta ...