TypeScript: The capability to deduce or derive values for a type from a constant object literal that is nested with non-distinct keys

I'm trying to figure out a way to utilize TS/IDE to display specific literal values from a style guide object, instead of just the inferred type. Here's an example:

const guide = {
  colors: {
    black: {
      medium: "#000000",
    },
    blue: {
      medium: "#3884F7",
      dark: "#053986",
    }
...
  },
  typography: {
    font: {
      family: "Commissioner",
      size: {
        xxs: "11px",
        xs: "12px",
        s: "14px"
...
    },
  },
};

Is there a way to specifically define guide.colors.blue.dark as "#053986" rather than just a generic string, without manually creating a new type object for the entire structure?

Answer №1

If you want the compiler to determine the most specific type from an object initializer, including the literal types of its property values, you can utilize a const assertion:

const guide = {
  colors: {
    black: {
      medium: "#000000",
    },
    blue: {
      medium: "#3884F7",
      dark: "#053986",
    }

  },
  typography: {
    font: {
      family: "Commissioner",
      size: {
        xxs: "11px",
        xs: "12px",
        s: "14px"

      },
    },
  }
} as const; // <-- const assertion

This will result in:

/* const guide: {
    readonly colors: {
        readonly black: {
            readonly medium: "#000000";
        };
        readonly blue: {
            readonly medium: "#3884F7";
            readonly dark: "#053986";
        };
    };
    readonly typography: {
        readonly font: {
            readonly family: "Commissioner";
            readonly size: {
                readonly xxs: "11px";
                readonly xs: "12px";
                readonly s: "14px";
            };
        };
    };
} */

Check out this Playground link with this 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

Angular 9: The instantiation of cyclic dependencies is not allowed

After transitioning from Angular 8 to Angular 9, I encountered an issue with a previously functioning HTTP communication service. The error message now reads: Error: Cannot instantiate cyclic dependency! HttpService at throwCyclicDependencyError (core ...

Webpack is having trouble identifying Node's process module

It has been more than ten years since I last worked with JavaScript, but recently I had an idea for an app that would be best implemented as a NodeJS app. As I delved into the modern JS ecosystem, like many others, I found myself thoroughly confused, haha. ...

Clear pagination - results generated by the clr-dg-page-size component

I'm currently developing an Angular 8 application using Clarity UI. Within my app, I have implemented a datagrid with pagination. My challenge lies in fetching data after changing the number of items per page, as there is no output provided by the Cl ...

Ionic causing delay in updating ngModel value in Angular 2

My ion-searchbar is set up like this: <ion-searchbar [(ngModel)]="searchQuery" (keyup.enter)="search();"></ion-searchbar> In the typescript file, the searchQuery variable is defined as follows: export class SearchPage { searchQuery: string ...

Prisma : what is the best way to retrieve all elements that correspond to a list of IDs?

I'm currently implementing Prisma with NextJs. Within my API, I am sending a list of numbers that represent the ID's of objects in the database. For example, if I receive the list [1, 2, 12], I want to retrieve the objects where the ID is eithe ...

When setupFilesAfterEnv is added, mock functions may not function properly in .test files

Upon including setupFilesAfterEnv in the jest.config.js like this: module.exports = { preset: 'ts-jest', testEnvironment: 'node', setupFilesAfterEnv: ["./test/setupAfterEnv.ts"] } The mock functions seem to sto ...

In the process of using SWRInfinite for React Infinite Scrolling, the initial call may be made

Can someone help me understand why my useGetItems hook, which imports the usePagination hook, keeps repeating the first call history every time I scroll? /items?_page=1&_limit=40 /items?_page=1&_limit=40 /items?_page=2&_limit=40 /items?_page=1 ...

The Generic Function's Return Type in Typescript

The latest addition of ReturnType in TypeScript 2.8 is a highly valuable feature that enables you to capture the return type of a specific function. function foo(e: number): number { return e; } type fooReturn = ReturnType<typeof foo>; // numbe ...

Mandatory classification eliminates understanding of function type

I'm currently trying to transform an optional argument from one type into a required one in my type definition. However, I am encountering some difficulties and can't seem to figure out what I'm doing wrong in the process. Would appreciate a ...

Using TypeScript, pass an image as a prop in a Styled Component

I am facing an issue with the code below that is supposed to display the "NoBillsLaptopPNG.src" image on the screen, but for some reason, the image is not showing up. The images are being imported correctly, so I'm unsure why the image is not appeari ...

Using Typescript in NextJS 13 application router, implement asynchronous fetching with async/await

Recently, I implemented a fetch feature using TypeScript for my NextJS 13 project. As I am still getting familiar with TypeScript, I wanted to double-check if my approach is correct and if there are any potential oversights. Here is the code snippet from ...

Combine Two Values within Model for Dropdown Menu

I am currently facing a situation where I have a select box that displays a list of users fetched from the backend. The select box is currently linked to the name property of my ng model. However, each user object in the list also contains an email proper ...

Issue with Typescript and eslint errors occurring exclusively in fresh code - Anticipated a colon.ts(1005)

Lately, in my extensive react-typescript project, I have encountered a peculiar issue. It seems that syntax errors are popping up everywhere, but only within the new code that I write. For instance, when creating a new component: import React from 're ...

Puppeteer with Typescript: Encountering issues during the transpilation process

The issue stems from the fact that I am unable to use Javascript directly due to Firebase Functions Node.JS version lacking support for Async/Await. As a workaround, I have converted the code into Typescript and am currently attempting to transpile it to c ...

creating a JSON array within a function

I am currently developing an Angular application and working on a component with the following method: createPath(node, currentPath = []){ if(node.parent !==null) { return createPath(node.parent, [node.data.name, ...currentPath]) } else { retu ...

Adding a constant to a Vue component

Currently working on developing an application using Vue and TypeScript. I'm focused on refactoring some aspects, particularly moving hard-coded strings from a template to a separate constant. What has been implemented is as follows: export const va ...

Creating fixtures with Playwright is a simple process that can greatly enhance

I have a requirement to set up fixtures where the first fixture is always available (acting as a base class) and the second fixture will vary in different test files (like a derived class). I've implemented the following code which seems to be working ...

Why does the Angular page not load on the first visit, but loads successfully on subsequent visits and opens without any issues?

I am currently in the process of converting a template to Angular that utilizes HTML, CSS, Bootstrap, JavaScript, and other similar technologies. Within the template, there is a loader function with a GIF animation embedded within it. Interestingly, upon ...

TypeScript properties for styled input component

As I venture into TS, I’ve been tasked with transitioning an existing JS code base to TS. One of the challenges I encountered involves a styled component in a file named style.js. import styled from "styled-components"; export const Container ...

Avoid selecting primary key column in TypeORM查询

Is it possible to exclude primary key columns from being selected in TypeORM? I've tried using the select false option, but it doesn't seem to work for these specific columns. Could it be because they are essential for identifying the entity or b ...