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

Learn how to utilize ng2-file-upload in Angular for uploading .ply files effortlessly!

I'm currently working on uploading various files using ng2-file-upload. I've been successful in uploading different file types like png and jpg, but I'm facing an issue with the .ply file extension. Can someone guide me on how to upload a fi ...

If a generic string argument is not specified as a string literal, it will not be narrowed unless it is the first argument

When the following code is executed, it works as intended and we can see that the arg variable is a string literal: const foo = <T extends string = string>(arg: T) => {}; foo('my string'); // const foo: <"my string">(arg ...

Struggling to access the properties of a Material-UI Button

import * as React from "react"; import { styled } from "@mui/material/styles"; import MuiButton from "@mui/material/Button"; import Slider from "@mui/material/Slider"; interface Props { type: "primary" | ...

The attempt to register a ServiceWorker for the angular scope was unsuccessful

I have encountered various solutions to this issue, some of which are not suitable for Angular and others simply do not work. In my quest to implement the "add to Homescreen" feature, I came across a helpful blog post (https://blog.betapage.co/how-to-add ...

Strategies for implementing classes in Typescript

I've been working on incorporating more classes into my project, and I recently created an interface and class for a model: export interface IIndexClient { id?: number; name?: string; user_id?: number; location_id?: number; mindbody_id?: nu ...

Is there a way to effectively eliminate an array of objects in JavaScript or TypeScript and alter the object structure simultaneously?

I am seeking solutions to restructure an object that has multiple arrays of objects so that I can access the object directly. console.log(value.data.summary[0].data) Instead of accessing arrays in this manner, I want to modify my data structure. Is there ...

Using an Angular variable with routerLink functionality

Is there a way to concatenate an id in my routerLink? <a routerLink="['/details', {{data.id}}]"> </a> is not working for me. Any suggestions on how to achieve this? Thank you in advance ...

TRPC error: The property 'useInfiniteQuery' is not found in the type '{ useQuery'

Issue with TRPC I am facing a problem with my tweetRouter that has a timeline query returning tweets and a NextCursor. However, I encounter an error when trying to access useInfiniteQuery in my components. ** Property 'useInfiniteQuery' does no ...

Show values in an angular template using an array

I want to showcase values of an array using *ngFor const blockData = [ {text: sampleText1, array: [val1]}, {text: sampleText2, array: [val2, dat2]}, {text: sampleText3, array: [val3, dat3]} ] <div *ngFor="let data of blockData"> ...

Error in Django framework: Attempting to insert a null value in the "hardware_type" column violates the not-null constraint

I have encountered a problem for which I have found solutions on Stack Overflow, but unfortunately, they do not work in my specific case. Here is a snippet of my code: models.py hardware_used = models.CharField(max_length=20, blank=True, null=True) core ...

Issues arise in Typescript single-page applications due to the use of application insights

Currently, I am developing a single-page HTML application using TypeScript in VSCode. Initially, the app was running smoothly without any errors or warnings. However, I decided to incorporate Azure Application Insight into the project. To integrate it, I ...

Declaring global types in a NX and NextJS monorepository for enhanced development consistency

I've been searching online to find a good solution for my issue, but so far I haven't had any luck. Currently, I have a NX monorepo with NextJS and I'm attempting to create a global types/ folder that can be accessed by all my apps and libs ...

Using ReactJS to pass an arrow function as a prop

Hey, I'm currently facing an issue where I need help creating a React component that can accept the following custom transformation: <CustomComponent transform={e=> {...e, text = e.text.toUpperCase()}}> </CustomComponent> I would real ...

Utilizing a created variable within the alert function: A guide

In order to display error messages in my app, I have created the following code: function createTimer(): void { if (!timer.start) { Alert.alert(strings.reminders['date-required']) return; } else if (!timer.end) { Alert.alert(strin ...

Leverage the nativeElement property within two separate components

Encountering an error in the autocomplete feature for Angular Maps (AGM), which reads: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined TypeError: Cannot read property 'nativeElement' of ...

TypeScript test framework for testing API calls in VS Code extensions

My VS Code extension in TypeScript uses the Axios library for API calls. I have written tests using the Mocha framework, which are run locally and through Github Actions. Recently, I integrated code coverage reporting with `c8` and I am looking to enhanc ...

Error in Angular Services due to Circular Dependency

I am encountering the following error message: Provider parse errors: Cannot instantiate cyclic dependency! Within my code, I have a Component dedicated to making HTTP calls to my backend server: backend.component.ts import { Http } from '@angul ...

I am currently facing an issue related to the length property. It is showing an ERROR TypeError: Cannot read property 'length' of undefined

Is it recommended to set the length to be inherited from Angular right? If so, why am I getting this error: "MyPostsComponent.html: 7 ERROR TypeError: Cannot read the 'length' of undefined property" when fileList.length is greater than 0? onFile ...

Modify a property within an object and then emit the entire object as an Observable

I currently have an object structured in the following way: const obj: SomeType = { images: {imageOrder1: imageLink, imageOrder2: imageLink}, imageOrder: [imageOrder1, imageOrder2] } The task at hand is to update each image within the obj.images array ...

The module 'crypto-js' or its corresponding type declarations cannot be located

I have a new project that involves generating and displaying "QR codes". In order to accomplish this, I needed to utilize a specific encoder function from the Crypto library. Crypto While attempting to use Crypto, I encountered the following error: Cannot ...