Converting an object to a dot notation string in Typescript types, excluding the innermost child

I am attempting to retrieve the appropriate typescript types using dot notation, excluding the deepest child.

After some searching, I came across a helpful resource at Typescript string dot notation of nested object, which partially solved my issue. However, it does not cover omitting the deepest child.

For example:

type TranslationType = {
  key1: {
    en: string,
  }
  sub: {
    key2: {
      en: string,
    }
  }
}

type PathsToStringProps<T> = T extends string
  ? []
  : {
      [K in Extract<keyof T, string>]: [K, ...PathsToStringProps<T[K]>]
    }[Extract<keyof T, string>]

type Join<T extends string[]> = T extends []
  ? never
  : T extends [infer F]
  ? F
  : T extends [infer F, ...infer R]
  ? F extends string
    ? `${F}.${Join<Extract<R, string[]>>}`
    : never
  : string

let value: Join<PathsToStringProps<TranslationType> // "key1.${string}" | "sub.key2.${string}"

The current output is

"key1.${string}" | "sub.key2.${string}"
but I am aiming for "key1" | "sub.key2".

Answer №1

Although this may not be my most polished Typescript code, it is getting the job done.

type Concatenate<T extends string[]> = T extends [string]
  ? never
  : T extends [infer F, ...infer R]
  ? F extends string
    ? Concatenate<Extract<R, string[]>> extends never
      ? `${F}`
      : `${F}.${Concatenate<Extract<R, string[]>>}`
    : never
  : string;

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

While performing compilation, Angular's ngFor triggers an error when used with SVG elements

I am attempting to create a recursive function of lines in order to generate a graph, but I am encountering a strange error in the console. It works fine on node.js. Below is the code snippet: <svg height = "200" width = "300"> ...

Displaying all notifications while using parameters in TypeScript

I am trying to display all of my notifications in HTML. The value is returned in res = response.json();, but my website only shows one notification, similar to the example in https://i.sstatic.net/ECbyx.png Let's start with this code: public event ...

"Disabling the checkbox in PrimeVue Tree does not hide it even when the selectable option is

Using Vue version 3.3.6 with Composition API script setup, Typescript, PrimeVue version 3.37.0, and PrimeFlex version 3.3.1, I am trying to implement a feature in my Tree component where I can disable certain checkboxes when the selectionMode is set to "ch ...

Tips for maintaining selected text while a modal window is active

So I'm currently working on a document writer and I'm utilizing document.execCommand to insert links. What I aim for is the ability for a user to select/highlight text, click a button to add a link to that specific text (via a modal), and then ha ...

Tips for utilizing an object key containing a dash ("-") within it

Here is an example of the object structure: { approved_for_syndication: 1 caption: "" copyright: "" media-metadata: (3) [{…}, {…}, {…}] subtype: "photo" } How can I properly a ...

Jasmine attempting to access a nonexistent property

I created a very basic component: import { Component } from '@angular/core'; @Component({ selector: 'loading', templateUrl: './loading.component.html', styleUrls: ['./loading.component.scss'] }) export ...

The Word Document is unable to locate the module or its associated type declarations

Encountering an issue while attempting to import a file from the src/assets/documents directory. https://i.sstatic.net/Gxq05.png Currently working on a React Project using Typescript. The goal is to import a file and use its value within an anchor tag fo ...

Guide to creating a Unit Test for an Angular Component with a TemplateRef as an Input

Looking to create unit tests for an Angular component that can toggle the visibility of contents passed as input. These inputs are expected to be defined as TemplateRef. my-component.component.ts @Component({ selector: "my-component", templateUrl ...

Having trouble retrieving values from Promise.allSettled on Node.js 12 using TypeScript version 3.8.3

Currently, I am delving into NodeJs 12 and exploring the Promise.allSettled() function along with its application. The code snippet that I have crafted allows me to display the status in the console, but there seems to be a hitch when attempting to print t ...

I find it strange that this warning message continues to pop up even though there is already a key prop assigned. It keeps saying: "Each child in a list should have a unique 'key'

As a newcomer to React, I find myself puzzled by the recurring appearance of this warning message: Warning: Each child in a list should have a unique "key" prop Even though there is already a key prop present on the element, why does this warn ...

Ensure to verify the slot for any included content to see if it is vacant

I'm currently facing a dilemma without a clear solution in sight. I have created some custom components that utilize content projection and multi slot transclusion. For instance, I have a Card (Bootstrap) and I want to customize elements like the he ...

Is there a different approach available since the array function "some" does not restrict type even when a type predicate is implemented?

It is expected that when using the array function "some" along with a type predicate and return statement, the TypeScript compiler would narrow down the type of dashArray. Is it reasonable to expect this behavior from the TypeScript compiler or am I incor ...

"TypeORM's createConnection function on MacOS with PG database returns a Pending status even when using

Running MacOS Catalina version 10.15.4 To replicate the issue, follow these steps using the quick guide: npm install typeorm --save npm install reflect-metadata --save npm install @types/node --save npm install pg --save npm install typeorm -g typeorm in ...

What is the best way to show the current values of predefined variables in VS Code, like "${workspaceFolder}" or "${fileWorkspaceFolder}"?

My current challenge involves debugging some Angular TypeScript source code in VS Code, and I suspect that the issue lies in the incorrect values of certain VS Code Variables - as mentioned here. I want to address this by checking the values of the VS Cod ...

Unauthorized access for POST request in WooCommerce API: 401 error

Let's start by examining the complete code to better understand the issue at hand. Here is the WooCommerce API authentication using the consumer key and secret from the file checkout.ts: this.WooCommerce = WC({ url:"http://localhost/ ...

Grunt is your go-to resource for instructions on executing these tasks before the main program

Before launching my app, I need to make sure a specific grunt task is executed first: node app.js I'm having trouble finding information on how to automatically run and complete a Grunt task before initiating a node command. In particular, I have T ...

Unexpected behavior with Angular 10 behavior subject - encountering null value after invoking .next(value) function

Can anyone help me solve the mystery of why my user value turns null after I log in? This is the login page where an API is called and the result is obtained as shown below: https://i.stack.imgur.com/kDjSy.png Here is the authentication service implemen ...

Issue with setting cookies in Node.js using Express

Recently I made the switch from regular JavaScript to TypeScript for my project. Everything seems to be functioning properly, except for session handling. This is the current setup of my project: Server.ts App.ts /db/mongo/MongoHandler.ts and some other ...

When using `onClick` in React, the old state value is not captured even though it may appear to be

In order to enhance the modularity and generality of my tabs and tab slots, I have developed a somewhat intricate setup. To achieve this, I opted to create a context and provider that expose methods for manipulating tabs and slots (where slots represent wh ...

Bring in personalized tag to TypeScript

I am working on a TypeScript file to generate an HTML page. Within this code, I want to import the module "model-viewer" and incorporate it into my project. import * as fs from "fs"; import prettier from "prettier"; import React from "react"; import ReactD ...