Can a type name be converted into a string representation for use as a template literal type?

Is there a way to retrieve the string representation of a type name in order to return a more concise compile error message from a type function?

I came across this solution (unfortunately, the article does not have anchor links so you will need to search for ErrorBrand) that demonstrates how to create an error message. Can we achieve the following using this method:

type ErrorBrand<Err extends string> = Readonly<{
  [k in Err]: void;
}>;

type MyErrorMsgType<T extends string> = ErrorBrand<`The following type caused an error - ${T}`>
type MyType = {field:string};

type GetStringNameOfType<T> = // converts Type to string name of type

type MyTypeName = GetStringNameOfType<MyType> // outputs 'MyType'

type MyTypeError = MyErrorMsgType<MyTypeName>
// output - The following type caused an error - MyType

Playground

Answer №1

Currently, TypeScript does not have a built-in feature that can convert type names into string literal types. There is no existing request for this specific feature, so you may consider filing one on the official GitHub repository.

It's unlikely that such a feature would be accepted, as type names are considered implementation details rather than something to be observable in the type system itself. The use cases provided in the example, while creative, are not aligned with the intended purpose of TypeScript type naming conventions.

The idea of having a utility type like TypeToString<T> could lead to unintended consequences and potential issues with assignability in a structural type system. For now, workarounds like using tuple types or experimental features like "invalid types" may suffice for displaying type names in messages without compromising the integrity of the type system.


If you are interested in exploring alternative ways to handle type names in TypeScript, you can review the related GitHub requests for insights and updates on any potential additions to the language.

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

Combining the values of a particular key with duplicate objects into a single object within an array of JSON objects using Angular and Typescript

I'm currently facing a challenge in my Angular project where I have an array of JSON objects. These objects are very similar, differing only in one key-value pair. My goal is to combine these similar objects into one while appending the varying values ...

How can you retrieve the keys of an object that conforms to an interface?

In the following demonstration, we have two objects - KEYS and KEYS2. When importing KEYS in index.ts, autocomplete suggestions are available for K1 and K2 because KEYS does not adhere to an interface. On the other hand, with KEYS2, autocomplete is not pr ...

Refining a collection of item elements by examining a string attribute, disregarding letter case differences

I'm working on a code snippet that generates item components from my list of objects (Frivillig). <app-frivillig-item *ngFor="let frivilligEl of frivillige" [frivillig]="frivilligEl"> </app-frivillig-item> Now, I have a new requireme ...

Nested arrays in an Angular interface

As a newcomer to Angular with a background in Java, I am accustomed to setting up classes as data structures for my information. However, after doing some research, I have learned that interfaces should be used instead. I am facing an issue understanding ...

How to arrange data in angular/typescript in either ascending or descending order based on object key

Hey there! I'm fairly new to Angular and have been working on developing a COVID-19 app using Angular. This app consists of two main components - the State component and the District component. The State component displays a table listing all states, ...

What is the best way to include the parameter set in the interceptor when making a post request?

-> Initially, I attempt to handle this scenario in the axios request interceptor; if the parameter is uber, then utilize a token. If the parameter is not uber, then do not use a token. -> Afterward, how can I specify uber as a parameter in the custo ...

Inject a cookie into the Axios interceptor for the request handler

I am in the process of setting up Axios to always include a request header Authorization with a value from the user's cookie. Here is my code: import axios, { AxiosRequestConfig, AxiosResponse} from 'axios'; import {useCookies} from "react-c ...

Exploring the features of NextJS version 13 with the benefits

Starting from the 13th step, SSR is utilized by default and in order to opt for client side rendering you must specify it at the top like so: 'use client' Currently, my setup involves TypeScript and styled-component integration. Take a look at ...

What is the method for extending props from React.HTMLProps<HTMLButtonElement>?

"react": "^17.0.2", "typescript": "^4.2.4" Can someone help me understand how to extend props from React.HTMLProps? import { FC, HTMLProps } from 'react' export interface SliderButtonProps extends HTMLPro ...

Using Typescript to extract elements from one array and create a new array

I have a set of elements "inputData" , and it appears as follows : [{code:"11" , name= "test1" , state:"active" , flag:"stat"}, {code:"145" , name= "test2" , state:"inactive" , flag:"pass"}, {code1:"785" , name= "test3" , state:"active" , flag:"stat"}, .. ...

Is it possible to customize a VSCode extension to function exclusively with certain programming languages?

Lately, I added a new extension to my VSCode setup that has proven to be quite beneficial for my workflow. If you're interested, you can find this helpful extension at This Repository. It allows you to easily highlight the starting and ending syntax ...

What is the most effective way to use a withLatestFrom within an effect when integrating a selector with props (MemoizedSelectorWithProps) sourced from the action?

I am struggling to utilize a selector with props (of type MemoizedSelectorWithProps) in an effect inside WithLatestFrom. The issue arises because the parameter for the selector (the props) is derived from the action payload, making it difficult for withLat ...

steps for creating a route with @input

I have created a component that utilizes an HTML attribute. I set it up so that users can specify the route when using this component within another component. However, every time I attempt to define the route value, I encounter a 'No provider for Rou ...

Updating Angular 8 Component and invoking ngOninit

Within my main component, I have 2 nested components. Each of these components contain forms with input fields and span elements. Users can edit the form by clicking on an edit button, or cancel the editing process using a cancel button. However, I need to ...

How to detect a click event in any area of an Angular2

Hey there, I'm new to typescript and angular 2 and I've encountered an error in my code. Can someone lend me a hand in fixing this? import { Component, HostListener } from '@angular/core' export class TooltipComponent { public sh ...

attempting to refine an array of objects using another array within it

I am currently filtering a group of objects in the following manner: [ { "Username":"00d9a7f4-0f0b-448b-91fc-fa5aef314d06", "Attributes":[ { "Name":"custom:organization", "Valu ...

Material UI is not capable of utilizing Props

I'm having trouble using the Checkbox component from Material UI. Even though I can't seem to use the normal props like defaultChecked or size="small", as it gives me the error TS2769: No overload matches this call. TS2769: No overload ...

Learn how to efficiently disable or enable a button in Angular depending on the selected radio button

In order to disable the button when the remarks are marked as failed. Here is an example scenario: Imagine there is an array containing two to four items. First example: ITEM 1 -> FAILED -> Remarks (required) ITEM 2 -> FAILED -> Remarks (r ...

Is it possible to use AngularJS promise scheduling with `async`/`await` syntax?

When working with AngularJS services, TypeScript often recommends that I switch my code to use async/await functions. https://i.sstatic.net/vks1i.png While I understand that using the await keyword is compatible with third-party promises because it essen ...

Exciting Angular feature: Dynamic Titles

I am working with an <i> tag <i class="actionicon icon-star" [ngClass]="{'yellow' : data.isLiked}" (click)="Like(data)" aria-hidden="true" title="Liked"></i> In my current set ...