Is the naming convention for parameterized types (T, U, V, W) in Generics adhered to by Typescript?

Is TypeScript following the same naming convention for parameterized types as other languages like C++ and Java, using T,U,V,W, or is there a mixed usage of conventions?

In the TS 2.8 release notes, we see examples like:

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;

Why use R instead of U here?

Then in another example:

type Unpacked<T> = T extends (infer U)[]
  ? U
  : T extends (...args: any[]) => infer U
  ? U
  : T extends Promise<infer U>
  ? U
  : T;

Why use U instead of R?

Further examples show inconsistent usage of variable names in generics.

The real question is: what naming conventions does TypeScript follow for generics? Are they similar to Java Generic Types or different?

Answer №1

(Mainly gathered from comments)

To provide a more objective response, one could refer to documentation outlining the "TypeScript Type Parameter Naming Convention" and compare it with the Java Generics tutorial document that was linked.

The official stand of the TypeScript design team appears to be that they do not enforce any specific naming conventions on others. According to discussions on GitHub issues microsoft/TypeScript#6168 and microsoft/TypeScript#878, as articulated in this comment:

"[I]n general we're not interested in deciding stylistic things for people. Saying that there's One Approved Style for TS goes against our philosophy that we're here to provide types for JS regardless of how you're writing it (within reasonable parameters, of course 😉)."

ESLint's naming-convention rule and TSLint's naming-convention rule can potentially help enforce type parameter naming conventions through linting; however, these rules are typically not enforced by default.


In comparison, let's examine the relevant section from the Java Generics tutorial:

Type Parameter Naming Conventions

Conventional type parameter names consist of single uppercase letters to differentiate them from variable names. This practice serves to avoid confusion between type variables and regular class or interface names.

Commonly used type parameter names include:

  • E - Element (commonly utilized in the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value
  • S,U,V etc. - Sequential types

These names are prevalent throughout the Java SE API and related lessons.

Note that the listed type parameter names are described as commonly used examples rather than strict mandates; they are descriptive rather than prescriptive.

The guideline suggesting the use of "single, uppercase letters" leans towards prescribing a convention to distinguish type names from variable names. However, it still reflects common practices rather than rigid rules.


One might conclude that an official or canonical type parameter naming convention does not exist in either TypeScript or Java, leaving any unofficial conventions subjective.

With regards to an unofficial convention within TypeScript, I personally perceive a trend toward using single uppercase characters that correspond to the represented entity. For instance:

  • T for "type," a frequently employed generic name;
  • K for "key" or P for "property," usually when constrained by PropertyKey or similar constructs;
  • V for "value," often paired with K for "key";
  • A for "arguments" and R for "return," aligning with function signatures like (...args: A) => R;
  • N for "number," S for "string," B for "boolean" when restricted by primitives;

These guidelines are flexible and subject to adaptation when clarity is paramount or potential ambiguity arises. In cases requiring multiple type parameters without collisions, modifications like appending numbers or prefixes may prove useful:

  • T0, T1, T2, T3, etc., to denote sequences of related types;
  • KT, KU, KV for discriminative key prefixes;

While deviations exist, using brief UpperCamelCase names can offer more descriptive insights into types, although this approach risks confusion with specific types instead of type parameters:

  • Key, Val, Prop, Arg, Ret, Type, This

It's advisable to avoid certain unconventional practices unless justified by exceptional circumstances:

  • Elaborate names resembling interface or class titles such as InputType or Properties;
  • Prepending an uppercase T to extended type names like TNotRecommended;
  • Initial lowercase letter beginnings like t, u, or myType;

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

Is it possible for TypeScript to mandate abstract constructor parameters?

This specific function is designed to take a constructor that requires a string argument and then outputs an instance of the constructed value T: function create<T>(constructor: new(value: string) => T): T { return new constructor("Hello& ...

Angular 6 and Typescript: How to Map Objects in Arrays within Arrays

We currently have two arrays named speisekarte (consisting of 10 objects) and essensplan (containing 8 objects). const speisekarte = [ { id: 11, name: 'Kabeljaufilet', price: 3.55, type: 'with fish' }, { id: 12, name: 'Spaghet ...

Issues with code functionality following subscription via a POST request

I'm currently facing an issue with a service that utilizes an HTTP post request to communicate with the database. Unfortunately, when I try to implement this in my .ts file, nothing seems to happen after subscribing to the post. The post itself works ...

What is the process for obtaining the ID of a selected node within ngx-graph?

Issue My challenge lies in using the ngx-graph library to create a flow chart within Angular 9. I am attempting to extract the id value of a node that has been clicked on. I have tried printing out "$event" and examining the PointerEvent object that appea ...

Developing UIs in React that change dynamically according to the radio button chosen

Problem Statement I am currently developing a web application feature that computes the heat insulation factor for a specific area. You can view the live demonstration on Codesandbox <a href="https://codesandbox.io/p/github/cloudmako09/btu-calc/main?im ...

Discover more efficient methods for utilizing generics in hierarchical objects within typescript

How can I optimize the structure of an object that contains nested objects in Typescript to minimize type repetitions? type itemType = { [key: string]: { [key: string]: { [key: string]: { [key: string]: string } }; }; }; ...

Tips for implementing loading functionality with Interceptor in Angular version 17

I am attempting to implement an interceptor in the latest version of Angular 17. export const loadingInterceptor: HttpInterceptorFn = (req, next,) => { const loadingService = inject(LoadingService); loadingService.show(); return next(req).pipe( finaliz ...

Converting a JSON string to an Object in Kotlin Multiplatform Mobile

In the past, I posed this query: Implementing generic method in interface that uses implementors class where an object could be transformed into a JSON string. However, my current aim is to reverse this process. Ideally, it would resemble the following: i ...

Utilize a list of Data Transfer Objects to populate a dynamic bar chart in recharts with

I received a BillingSummaryDTO object from a Rest API using Typescript: export interface BillingSummaryDTO { paid?: number, outstanding?: number, pastDue?: number, cancelled?: number, createdAt?: Moment | null, } export async function ...

Pass the parameter name to the controller using the Change function in Angular 2

When creating a string from multiple inputs, I have a requirement to include the name of the input element as the second parameter in a function. <input [(ngModel)]="programSearched" name="programSearched"(ngModelChange)="stringBuilderOnChangeMaker(pro ...

Adjustable angular-design sidebar with collapsible sections

My goal is to create a mat-drawer that can be resized and will collapse its content when it reaches a certain min-width. I've implemented this library to make the mat-drawer resizeable, which seems to be working well. The issue I'm encountering ...

Initializing variables in Angular2 templates

I am facing an issue where, upon running the application, the console displays all the logs from the ngOnInit function, but the actual view only shows a skeleton without the component variables and text from l18n. It seems like the ngOnInit is not working ...

Exploring the art of styling in Angular6

I am looking to change the text color when a specific ID is clicked <nav class="navbar "> <ul class="navbar-nav"> <li *ngFor="let item of items"> <a class="nav-link" >{{item.title}}</a> ...

Tips on adjusting sticky behavior for responsiveness using bootstrap-4

In my project, I am utilizing angular with bootstrap. The header of the project consists of two parts and a content area. However, when the resolution is small, the header wraps. Check out the header and content on large screens View the header and conte ...

Child routes cannot be included when ..., so make sure to specify "..." in the parent route path

I've been working on setting up child routing within my project, and here is the current folder structure I have: app |--home/ | |--home.component.ts |--login/ | |--login.ts |--appShell/ | |--app.component.ts |--apps/ |- ...

Is your async function lacking a return statement?

After completing the development of a new method for a bug I encountered, I noticed something interesting. Despite the fact that there is a potential scenario where the function may not return anything, the compiler did not flag any errors. It got me think ...

Having issues with an Angular reactive form that includes a custom form-level validator and the 'blur' updateOn option?

Having issues combining the following: angular reactive form custom validator at form level (cross-field validator) usage of the 'updateOn' option set to 'blur' A demonstration of the problem can be found in this simple stackblitz: h ...

When the browser screen is minimized, the menu bar toggler in my Angular project stops functioning properly. I rely on Bootstrap features within Angular to handle this

When the browser is at full-screen mode, HTML works perfectly. However, when I resize the browser to a smaller size, the navbar disappears and a toggle is shown - which is the expected behavior. If I click on the toggle, the menu list should be displayed ...

The concept of RxJS's catchError function involves the return of a versatile

It's interesting that catchError is returning an Observable union type as Observable<{} | Page} instead of just Observable<Page>. The error message from the compiler reads: Type 'Observable<{} | Page>' is not assignable to t ...

Guide on how to run functions in Angular 2+ directly from the console?

My application is designed to operate within a chromium browser using chromiumfx. With chromiumfx, you can seamlessly run any JavaScript functions as if you were working in a console environment. Here's a snippet of my code: import { Component } f ...