A TypeScript type that is either a string or number, but never simply a string alone

I am attempting to create a type that can be either string | number or just number, but never solely string. I made an attempt below, but it seems like the string | number case is reduced to just number. Is there a way to achieve this without such reduction?

type StringOrNumberOrJustNumber<T extends string | number = string | number>
  = T extends number ? T : never;

// Expected output: "string | number"
type StringOrNumber = StringOrNumberOrJustNumber<string | number>;

// Desired output: "never" (or an error)
type JustString = StringOrNumberOrJustNumber<string>;

// Expected output: "number"
type JustNumber = StringOrNumberOrJustNumber<number>;

Playground Link

Answer №1

To implement this, you will need to add another conditional statement and encapsulate the types being compared in brackets to create tuples. This prevents them from being considered as naked types, ensuring that they do not get distributed by the conditional logic.

It's important to note that the order of comparison in the second conditional should be [string | number] extends [T], not the other way around. This is because the goal is to determine if [string | number] can be assigned to [T], rather than checking if [T] can be assigned to

[string | number]</code, since both <code>[string]
and [number] are assignable to [string | number].

type StringOrNumberOrJustNumber<T extends string | number = string | number> = [T] extends [number] ? T : [string | number] extends [T] ? T : never;

Unfortunately, it doesn't seem feasible to trigger an error when only a string is provided.

In any case, feel free to explore the updated playgroundhere.

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

How can Karma unit tests with Jasmine in a TypeScript Node project accurately measure code coverage, even with external dependencies?

We have a unique situation with the code coverage of our project involving a node dependency. It's important to note that the npm dependency source code is actually part of our project, as we are responsible for its development and publication. Here&a ...

React.js with Typescript is throwing an error stating that a property does not exist on the child component

Currently, I am working with React in conjunction with typescript 2.3.4. I keep encountering the error TS2339: Property 'name' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'. This issue arises wh ...

What's the reason for the malfunction of  ?

How can I add space between firstname and lastname using   in my code? Despite setting the character set to utf-8, the space is not being rendered correctly. I even tried using tab space, but it didn't work as expected. export class AppCompone ...

What steps should I take to address this issue using IONIC and TypeScript?

Running into an issue with my TypeScript code for an Ionic project. I'm attempting to pass the value of the variable (this.currentroom) from the getCurrentRoom() function to another function (getUser()) but it's not working. Here's my chat s ...

Angular 6 is throwing an ERROR TypeError because it is unable to access the property 'length' of a null object

Recently delving into Angular 6, I've encountered an issue with two components: app.component.ts and products.component.ts, as well as a service file. In the products component, I am receiving a JSON response in the ngOnChanges method. My goal is to ...

Typescript error encountered while attempting to fetch repository from Redis OM

I'm currently working on developing a shopping cart system with the use of expressjs, typescript, and redis OM for the in-memory database. As I created a schema using Redis OM, I encountered an error The error message says: 'Property 'fetc ...

Altering the background color of an individual mat-card component in an Angular application

Here is the representation of my mat-card list in my Angular application: <div [ngClass]="verticalResultsBarStyle"> <div class="innerDiv"> <mat-card [ngClass]="barStyle" *ngFor="let card of obs | async | paginate: { id: 'paginato ...

Error encountered when packaging WebAssembly using Rollup

When I use wasm-pack to compile some rust code into webassembly, specifically with the option --target browser (which is the default), these are the files that I see in typescript/deps/ed25519xp: ed25519xp_bg.wasm ed25519xp_bg.d.ts ed25519xp.d.ts ed25519 ...

Angular4 Blueprint

Here is a simple demonstration of ngTemplate that I have coded: <div> <ng-container [ngTemplateOutlet] ="template1"> </ng-container></div> Below are the template examples: <ng-template #template1> This is the 1st template & ...

Looking for a JavaScript library to display 3D models

I am looking for a JavaScript library that can create 3D geometric shapes and display them within a div. Ideally, I would like the ability to export the shapes as jpg files or similar. Take a look at this example of a 3D cube: 3d cube ...

Using TypeScript with Styled Components .attrs

I'm a bit perplexed about using the .attrs() function in conjunction with TypeScript. Let's consider the code snippet below: BottleBar.tsx: interface IBottleComponentProps { fill?: boolean } const BottleComponent = styled.div.attrs<IBottl ...

The Element type does no feature a Typescript property

Despite my attempts to include a declaration file and various other solutions, I'm still struggling with this issue: The goal is to define the visible property as a function on the HTML Element object. However, the linter keeps flagging visible with ...

Error: Unable to access 'useRef' property of null object due to TypeError

Currently, I am using a combination of Next.js, TypeScript, sanity, and tailwindcss in my project. I have come across an error while attempting to utilize the react-hook-form. I have experimented with different approaches: Converting the Post function in ...

Error in Typescript occurring with a custom typography element

I recently developed a simple typography component for my React project and it's causing a Typescript error that's puzzling me a bit. Typography Component Code import clsx from 'clsx'; const sizeVariants = { h1: 'h1', ...

Version 4 of Typescript is experiencing crashes when spreading optional arguments

Previously with TypeScript 3.9+, this setup was functioning perfectly: type keys = | 'one' | 'another' | 'yet_another'; type variables = { 'another': { count: number } 'yet_another': { ...

"Enhancing user experience with MaterialUI Rating feature combined with TextField bordered outline for effortless input

I'm currently working on developing a custom Rating component that features a border with a label similar to the outlined border of a TextField. I came across some helpful insights in this and this questions, which suggest using a TextField along with ...

Can a unique intrinsic type be created from scratch?

Ever since template literals were introduced in Typescript (PR), we've had access to various useful functions in our types: Uppercase Lowercase Capitalize Uncapitalize For more information, refer to the official documentation. Although it may seem ...

Updating objects in state dynamically

I have a form with multiple pages and I want to dynamically update the values obtained from it. To achieve this, I created a state variable called endResult which is initialized as an object with empty strings for each desired element. To illustrate, here ...

How can I extract a value from an object that is readonly, using a formatted string as the key?

I encountered a situation where I have code resembling the following snippet. It involves an object called errorMessages and multiple fields. Each field corresponds to various error messages in the errorMessages object, but using a formatted string to retr ...

Turned off SWC as a substitute for Babel due to the specific Babel setup in Next.js version 14

While working on my Next.js 14 project, I encountered an issue when running npm run dev. The error message I received is as follows: npm run dev > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f3226722f302d2b39303336301f6 ...