Determine the category of a nested key within a different type

I'm currently utilizing graphql-codegen which generates types in the following structure:

type Price = {
  onetime: number;
  monthtly: number;
};

type CarModel = {
  price: Price;
  name: string;
};

type Car = {
  model: CarModel;
  someOtherAttribute: string;
};

type MyCarQuery = Pick<Car, "someOtherAttribute"> & {
  model: Pick<CarModel, "name"> & {
    price: Pick<Price, "onetime">;
  };
};

I am interested in isolating the type of

MyCarQuery -> model -> price
and using it independently. Essentially, I want to create a type definition for Pick<Price, "onetime"> without redundant definitions.

Is there a method to achieve this without duplicating the types?

Answer №1

Here is the solution you're searching for:

type TheType = MyCarQuery["model"]["price"];

Check it out in the playground.

This assignment defines TheType as {onetime: number}, but if you modify Price to have onetime as a string, then TheType will become {onetime: string}.

Unfortunately, there isn't an explicit reference in the Handbook for this concept, so I learned about it from various Stack Overflow responses.

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

What is the method to assert that two arguments are equal within a function?

When working with TypeScript, you can pass a value to a function and have that function assert the value is true for type narrowing. For example: function assertTrue(v: unknown, message: string): asserts v { if (!v) { throw new MySpecialError(message ...

What sets apart extending and intersecting interfaces in TypeScript?

If we have the following type defined: interface Shape { color: string; } Now, let's explore two different methods to add extra properties to this type: Using Extension interface Square extends Shape { sideLength: number; } Using Intersection ...

Listening for Angular 2 router events

How can I detect state changes in Angular 2 router? In Angular 1.x, I used the following event: $rootScope.$on('$stateChangeStart', function(event,toState,toParams,fromState,fromParams, options){ ... }) In Angular 2, using the window.addEv ...

Is there a way to dynamically exclude files from the TypeScript compiler?

Currently, I am in the process of setting up a node/typescript server for a real-time application. Both my server and client are located within the same folder. My goal is to exclude "src/client" from the typescript compiler when executing the "server:dev ...

The ASP.NET Core Web API successfully sends back a response, but unfortunately, the frontend is only seeing an empty value along with a status code of 200 (OK)

Currently, I am delving into the world of web APIs and have stumbled upon a perplexing issue that requires assistance. I have an active ASP.NET Core Web API at the backend, while at the frontend, an Angular application (running on version 15.1.5) is in pl ...

Currently, my goal is to create PDFs using Angular

<button class="print" (click)="generatePDF()">Generate PDF</button> Code to Generate PDF generatePDF(): void { const element = document.getElementById('mainPrint') as HTMLElement; const imgWidth = 210; ...

Issue with data-* attributes in MaterialUI React component causing TypeScript error

I am encountering an issue while attempting to assign a data-testid attribute to a Material-UI Select component. The Typescript error I am facing is as follows: Type '{ "data-testid": string; }' is not compatible with type 'HTMLAttributes&a ...

Advanced automatic type inference for object literals in TypeScript

When working with TypeScript, I often declare generic functions using the syntax: const fn: <T>(arg: T)=>Partial<T> While TypeScript can sometimes infer the type parameter of a function based on its parameters, I find myself wondering if t ...

Having trouble running `npm start` on my NodeJs project

Hi everyone, I could really use some help with the npm start command. I am currently working on a Node.js project with TypeScript on Windows 7-64, but I'm encountering errors when trying to start it. If you can assist, please check out the following ...

Typescript function incorrectly returns Protractor's "element.all" output as Promise<string> instead of Promise<string[]>

Kindly review the code snippet provided below. The function getAllGroupIds() is designed to return an array of IDs belonging to "group" elements. The goal is to retrieve all the group-ids both before and after a test action, in order to compare them. Howe ...

What is the connection between tsconfig.json and typings.json files?

I recently acquired a .NET MVC sample application that came with Angular2-final. Within the project, I noticed a typings.json file at the root and a tsconfig.json file in the ng2 app directory. What is the connection between these two files? Is this the mo ...

Error message in Ionic 2: "Property is not found on type"

Currently, I am working on a project in Ionic 2 and have encountered a stumbling block with a seemingly simple task. My issue lies with a Textbox where I aim to input text that will then be displayed. I found some code on a website (http://www.tizag.com/j ...

What is the best way to merge multiple nested angular flattening operators together?

I am facing a challenge in utilizing the outcomes of Observables from various functions. Some of these functions must be executed sequentially, while others can run independently. Additionally, I need to pass the result of the initial function to some nest ...

Using createStackNavigator along with createBottomTabNavigator in React Navigation version 5

I have recently started working with react native and I am using the latest version of react-navigation (v.5) in my react-native application. However, I encountered errors when trying to use createStackNavigator and createBottomTabNavigator together within ...

During the execution of Jest tests, a singular module is experiencing undefined imports

Encountering an unusual issue with Jest, create-react-app, and typescript. Out of the blue, Jest has stopped importing my "./ProcessStore" module correctly. This module is a dependency of something that is being imported in my tests. The error message in ...

How can we create a unique type in Typescript for a callback that is void of any return value?

When it comes to safe callbacks, the ideal scenario is for the function to return either undefined or nothing at all. Let's test this with the following scenarios: declare const fn1: (cb: () => void) => void; fn1(() => '123'); // ...

Customizing a generic method in typescript

I am currently working on developing a base class called AbstractQuery, which will serve as a parent class to other classes that inherit from it. The goal is to override certain methods within the child classes. class AbstractQuery { public before< ...

Retrieving Data from Repeated Component in Angular 6

Need Help with Reading Values from Repeating Control in Angular 6 I am struggling to retrieve the value of a form field in the TS file. Can someone please assist me with this? This section contains repeating blocks where you can click "add" and it will g ...

The ngxpagination template is currently experiencing issues with filtering and pagination functionality

I have encountered an issue with my custom pagination template using ngx-pagination. Everything works fine until I introduce a filter pipe alongside the pagination. The problem arises when the filtered data set is not properly paginated - instead of displa ...

Error message: "Mismatched data types in Formik errors when utilizing TypeScript"

I have a customized input component for formik which includes an error label if one exists. When I print it like this: {errors[field.name]}, it works. However, {t(errors[field.name]?.toLocaleString())} does not work. import { FieldProps, FormikErrors } ...