Matching TypeScript against the resulting type of a string literal template

My type declaration looks like this:

type To_String<N extends number> = `${N}`

I have created a Type that maps the resulting string number as follows:

type Remap<Number>
    = Number extends '0'
    ? 'is zero'
    : Number extends '1'
    ? 'is one'
    : Number extends '2'
    ? 'is two'
    : 'other number'

type One = Remap<To_String<1>> // 'is one'
type Other = Remap<To_String<5>> // 'other number'

Everything seems to be working fine so far, but then I encounter an issue when trying to pass just 'number', such as when attempting to call a function that returns a 'number'. I'm struggling to figure out how to match against the resulting type that is represented in backticks and matches against a string:

type Remap<Number>
    // = Number extends `${number}` - attempt that catches all values
    = Number extends '${number}' // not matched against string version
    ? 'is Template literal result'
    : Number extends '1'
    ? 'is one'
    : Number extends '2'
    ? 'is two'
    : 'other number'

// this gives a result type enclosed in backticks that still passes as a string
type Template_String_Result = To_String<number> // `${number}`
// an attempt that fails to catch the top match clause
type Non_Literal_Number = Remap<To_String<number>>

Is there a way to match against this Template literal string?

Answer №1

If the query is understood correctly, the intention is to utilize ​`${number}` extends Number as the initial condition, given that Number is a generic parameter that may encompass a wider range than ${number} (even though in the specific scenario, it may not). On the contrary, if the test is reversed, it still holds validity because anything that fits ${number} would also align with something wider than ${number}.

type Remap<Number>
    = `${number}` extends Number
    ? "is Template literal result"
    : Number extends "1"
    ? "is one"
    : Number extends "2"
    ? "is two"
    : "other number"

The outcomes would then be as follows, which seem to align with the expected results:

type One = Remap<To_String<1>>
//   ^? type One = "is one"
type Two = Remap<To_String<2>>
//   ^? type Two = "is two"
type Other = Remap<To_String<5>>
//   ^? type Other = "other number"
type Non_Literal_Number = Remap<To_String<number>>
//   ^? type Non_Literal_Number = "is Template Literal result"

Playground link

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

When creating an async function, the type of return value must be the universal Promise<T> type

https://i.stack.imgur.com/MhNuX.png Can you explain why TSlint continues to show the error message "The return type of an async function or method must be the global Promise type"? I'm confused about what the issue might be. UPDATE: https://i.stac ...

What is the best way to retrieve information utilizing Http.get within my project?

I have a TypeScript file containing user data: File path: quickstart-muster/app/mock/user.mock.ts import {User} from "../user"; export const USERS:User[]=[ new User(....); ]; I have a service set up at: quickstart-muster/app/services/user.service.ts ...

Create a new instance of the TypeScript singleton for each unit test

I have a TypeScript singleton class structured like this: export default class MySingleton { private constructor({ prop1, prop2, ... }: MySingletonConfig) { this.prop1 = prop1 ?? 'defaultProp1'; this.prop2 = prop2; ...

Steps for enabling a function to return an undefined type

After extensive review, I have discovered that TypeScript has numerous hidden nuances, which make it less strict and accurate. I prefer to utilize 'undefined' as the return type for functions because it accurately reflects the reality of the sit ...

Navigating the pathway to retrieving variables within an Angular Component function

export class MapsComponent implements OnInit { @ViewChild('googleMap') gmapElement: any; map: google.maps.Map; data = "initialised"; ngOnInit() { var directionsService = new google.maps.DirectionsService; ...

Implementing a boolean toggle method in Typescript for a class property

Hello there, fellow programmers! I am interested in changing the value of a class field using a method. I have a button in Angular that, when clicked, triggers the onSave() method: export class CourseComponent { isActive:boolean; onSave() { ...

Exploring Angular 4: Embracing the Power of Observables

I am currently working on a project that involves loading and selecting clients (not users, but more like customers). However, I have encountered an issue where I am unable to subscribe to the Observables being loaded in my component. Despite trying vario ...

Unable to verify Angular 5 identity

After authentication, the application should redirect to another page. However, despite successful authentication according to the logs, the redirection does not occur. What could be causing this issue? auth.guard.ts: import { Injectable } from &apos ...

Pause and anticipate the occurrence of AdMob's complimentary video reward event within a defined function in Ionic/Typescript

In my ionic app, I have a function that determines if the user has watched a reward video to access another function: let canUseThisFunction = await this.someService.canUseFunction(); if(canUseThisFunction){ console.log("can use"); } else { cons ...

Tips for implementing a real-time search feature in Angular

I require assistance. I am attempting to perform a live search using the following code: when text is entered into an input, I want my targetListOptions array, which is used in a select dropdown, to update accordingly. The code runs without errors, but not ...

Managing component composition in React/TypeScript: What's the best way to approach it?

I am brand new to the world of typescript, so please be patient with me. My objective is to transform this react component: interface ButtonProps {...} const Button: React.FC<ButtonProps> = ({ children, href, value as = 'button', ...

Having trouble retrieving values from the getEntry method in Contentful

How can I retrieve an entry from contentful using Contentful v10 with Node.js 18? I am having trouble accessing the value in getEntry(). interface Example { contentTypeId: 'item' fields:{ title: EntryFeildTypes.Text rate: EntryFeildType ...

Scrolling the mouse wheel on Angular 2 Typescript Highcharts Highmap

I'm currently exploring if it's possible to subscribe to the zooming event in a Highmap using Angular 2 with Typescript for Highcharts/Highmap, or possibly even to a mouse wheel scrolling event. @HostListener('scroll', ['$event&a ...

best method for implementing a TypeScript object

I've been searching high and low, but I can't seem to find the exact answer I need. Please inform me if my question has already been asked. My goal is to construct an object in TypeScript that includes attributes of custom types. The issue I&ap ...

What exactly does Type refer to in Angular 2?

I keep encountering the Type keyword in various parts of the documentation. For instance, in this link, it mentions that the ComponentRef has a property called componentType which is of type Type<any>. Upon further investigation, I stumbled upon this ...

Tips for preserving data upon page refresh in angular 2/4

As a newcomer to Angular2/4, I am facing an issue where the details fetched and saved in my interface are disappearing upon interface refresh. How can this problem be resolved without losing the interface details after a refresh? Here is my Login.componen ...

What is the best way to access the input element of ng-content from the parent component?

Creating a unique component in the following structure <div class="custom-search-field" [ngClass]="{'expanding': expanding}"> <ng-content></ng-content> </div> When using this component, users are expected to include ...

The data type 'string | boolean | null' cannot be assigned to type 'boolean'. Specifically, the type 'null' cannot be assigned to type 'boolean'

Can you spot the issue in this code snippet? isAuthenticated(): boolean { var token = localStorage.getItem(ACCESS_TOKEN_KEY); return token && !this.jwtHelper.isTokenExpired(token); } Error: The variable is returning a type of 'string | bo ...

What could be causing my component to not refresh when used as a child?

I have been experimenting with some code to track rerenders. The initial approach failed when passing <MyComponent> as a child component. it("should return the same object after parent component rerenders", async () => { jest.useF ...

Can you explain the process of utilizing Angular databinding to display nested information?

I'm facing a challenge with databinding when working with nested arrays in multiple timeslots and windows. Despite understanding the basics, I can't seem to make it work no matter how I try different approaches. It's really frustrating not k ...