Can a type be referenced using the generic name?

My selection includes:

export type DocumentType =
  | Item
  | List
  | User

export type DocumentInputType =
  | ItemInputType
  | ListInputType
  | UserInputType

I want to develop a feature that can determine the input type based on the document type without requiring an additional generic parameter. Is this feasible?

type Documents<DocType extends DocumentType> = {
  data: DocType[]
  createDocument: (input: <<This is where I want the corresponding DocumentInputType>>) => void
}

Answer №1

Learn how to utilize a conditional type:

type DocumentInputTypeOf<DocType extends DocumentType>
  = DocType extends Item ? ItemInputType
  : DocType extends List ? ListInputType
  :                        UserInputType

type Documents<DocType extends DocumentType> = {
  data: DocType[]
  createDocument: (input: DocumentInputTypeOf<DocType>) => void
}

Answer №2

My approach to writing this would be as follows:

export type DocumentsUnion =
  | {data: Item[], createDocument: (input: ItemInputType) => void}
  | {data: List[], createDocument: (input: ListInputType) => void}
  | {data: User[], createDocument: (input: UserInputType) => void}

// Defining types based on the union of data in DocumentsUnion
export type DocumentType = DocumentsUnion['data'][number]
export type DocumentInputType = DocumentsUnion['createDocument'] extends infer F ? F extends (input: infer U) => void ? U : never : never

// Extracting documents based on specified type T
export type Documents<T extends DocumentType> = Extract<DocumentsUnion, {data: T[]}>

Check it out here!

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 reason behind the ability to reassign an incompatible function to another in TypeScript?

I discovered this question while using the following guide: https://basarat.gitbooks.io/typescript/content/docs/types/type-compatibility.html#types-of-arguments. Here is an example snippet of code: /** Type Heirarchy */ interface Point2D { x: number; y: ...

Unable to access component properties through react-redux

Context: A React Native application utilizing Redux for managing complexity. Versions: typescript v3.0.3 react-native v0.56.0 redux v4.0.0 @types/react-redux v6.0.9 @types/redux v3.6.0 Issue: The main JSX component in my app is unable to access proper ...

Exploring Angular2's ability to interpret directive templates using the ng-container

Recently delving into angular2, I ventured into creating dynamic forms and generating fields by following the guide provided in this URL. The result was as expected. The dynamic form component renders each field one by one using ng-container, like shown b ...

Having Trouble Retrieving Data from Observable in Angular 2 and Typescript

I've encountered a promise error when trying to access a variable that receives data from an observable. Here's an example: Within my component, I have defined the Stat class: export class Stats { name: string; percentage: number; constru ...

What is the best way to organize information in a table based on the date

This is my data table https://i.stack.imgur.com/1DNlj.png in the displayed table, the registration dates are sorted with the oldest date at the top. However, I aim to have the newest data displayed first. Below is the code snippet I am using: this.dataSo ...

The benefits of exporting a component from one module and using it in another module

After putting in long hours trying to figure this out on my own, I've finally decided to seek help from the community. Thank you in advance for any assistance! I have a Web Projects Module that utilizes a Webpage Component. Within the Webprojects Mod ...

Creating custom typings in a typings.d.ts file does not address the issue of importing a JavaScript library

I'm attempting to integrate the Parse-server JS sdk into an angular 8 application, but no matter what approach I take, I encounter errors. Here is what I have tried: Creating custom typings.d.ts files with declare var parse: any; Installing the @ty ...

Ways to effectively implement a function type specified in an interface

Consider the following interface: interface MyProps { onEvent: (name: string, data: any) => void; } Is there a way to utilize the function type in order to avoid unused parameter errors during compilation? eventHandler = (name: string, data: any) = ...

Angular selects the initial three arrays out of an array

In my code, I have a collection of arrays that are nested within another array. My task is to extract the first three arrays from this collection. For instance, consider the following example: [{[1]},{[2]},{[3]},{[4]}] I apologize for not presenting a p ...

Unable to retrieve rxjs resource

After upgrading to rxjs 5.4.3, I encountered an error in the browser. Despite having "rxjs": "5.4.3" installed in my package.json, I cannot seem to resolve this error message. Here's the content of my ts file: import { Injectable ...

Using ngModel instead of value to bind a custom Angular directive for currency input

Currently, I am using a specialized mat-input-currency format directive to automatically convert my field inputs into currency. You can find the npm repository here. However, the directive binds the element data to [value] of the input, and I require it t ...

Exploring React State Management: Leveraging the Context API as a centralized store for

Currently, I am developing a React web application using TypeScript. To enhance the State Management, I decided to implement React Hooks and Context API by following a concise tutorial that I came across here. Despite diligently following the tutorial, my ...

The ngOnChanges lifecycle hook is triggered only once upon initial rendering

While working with @Input() data coming from the parent component, I am utilizing ngOnChanges to detect any changes. However, it seems that the method only triggers once. Even though the current value is updated, the previous value remains undefined. Below ...

Tips for applying personalized CSS to individual Toast notifications in Angular

MY QUESTION : I am looking to customize the CSS of a single toast used in Angular components. While there may be multiple toasts, I specifically want to style one particular toast differently. For example, the toast image can be viewed here: example toast ...

Where should I place the function URL and the path to credentials.json when attempting to call a Google Cloud Function with CloudFunctionsServiceClient?

I found this code snippet on here: /** * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. The name of the function to be called. */ // const name = 'abc123' /** * Required. Input to ...

Why am I getting the "Cannot locate control by name" error in my Angular 9 application?

Currently, I am developing a "Tasks" application using Angular 9 and PHP. I encountered a Error: Cannot find control with name: <control name> issue while attempting to pre-fill the update form with existing data. Here is how the form is structured: ...

What is the best way to define a model class within my Angular 2 component using TypeScript?

As I delve into Angular 2 and TypeScript, I am keen on adopting best practices. I have decided to move away from a simple JavaScript model ({ }) in favor of creating a TypeScript class. However, it seems that Angular 2 is not very fond of my approach. T ...

Using Typescript to implement a conditional return type and ensuring that the value types are consistent together

I am working with a useSelectedToggle hook that helps in connecting the UI state to the open/closed status of a dialog where it will be displayed. The toggle defines the value as (T) when it is open, and null when it is closed. How can I enforce stricter ...

The inclusion of HttpClient is causing issues with the functionality of my component

Currently, I am facing an issue with my Angular service called ConnexionService. The problem arises when I try to incorporate CSV files into this service using HttpClient. Strangely, the component associated with this service fails to display once HttpClie ...

Mapping two objects of the same shape to each other recursively using TypeScript

I receive regular data from a specific source. This data consists of nested objects containing numerical values. For example: { a: 1, b: { c: 2, d: 3.1, }, } My objective is to organize this data into multiple TimeSeries objects of the same struct ...