TypeScript overload does not take into account the second choice

Here is the method signature I am working with:

class CustomClass<T> {
  sanitize (value: unknown): ReturnType<T>
  sanitize (value: unknown[]): ReturnType<T>[]
  sanitize (value: unknown | unknown[]): ReturnType<T> | ReturnType<T>[] {
    // ...
  }
}

type ReturnType<T> =
    T extends String ? string
  : T extends Number ? number
  : T extends Boolean ? boolean
  : T

Despite how I try to use this method, the IntelliSense feature does not recognize that it should return an array:

const exampleOne = new CustomClass<Number>().sanitize('5') // returns a number
const exampleTwo = new CustomClass<Number>().sanitize(['5']) // returns a number instead of a number[]

Is there something I'm missing or doing incorrectly here?

Answer №1

I decided to test this out on a TypeScript playground. My theory was that the issue stemmed from the fact that unknown actually encompasses unknown[].

However, when I reversed the order of the definitions to be more specific, it resulted in the desired outcome:

class Bar<U> {
  process (data: unknown[]): outputValue<U>[]
  process (data: unknown): outputValue<U>
  process (data: unknown | unknown[]): outputValue<U> | outputValue<U>[] {
    return 'bar' as any;
  }
}

Answer №2

Give this a try and see if it meets your needs

class Bar<U> {
  clean<V extends any | any[]>(input: V): Validate<U, V> {
    return 'bar' as any
  }
}

type Validate<U, V> = V extends any[]
  ? checkType<U>[]
  : checkType<U>

type checkType<U> = U extends String
  ? string
  : U extends Number
  ? number
  : U extends Boolean
  ? boolean
  : U

const x = new Bar<Number>().clean('10') // number
const y = new Bar<Number>().clean(['10']) // number[]

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

Utilize the gsap ScrollTrigger in conjunction with React's useRef() and Typescript, encountering issues with type mism

Recently, I've been trying to add some animation to a simple React Component using the GreenSock ScrollTrigger plugin. However, I ran into an issue due to types mismatch in my Typescript project. Here's a snippet of the code: import React, {useRe ...

A method for comparing two arrays containing identical objects and then storing the results in a variable

I have an item stored within two other items called formKeyValues and form formKeyValues https://i.stack.imgur.com/nRfiu.png form https://i.stack.imgur.com/eDpid.png I am looking to extract only the keys and values from formKeyValues and place them in ...

Filter out all elements in an array except for one from a JSON response using Angular 2

After receiving a JSON response from a server via HTTP GET, the data structure looks like this: { searchType: "search_1", overview: [ "Bed", "BedSheets", "BedLinen", .. ...

Monitor the change in values upon pressing the submit button on Angular

I am currently working with an edit form that contains data in the input fields. <ng-form #infoForm="ngForm" novalidate> <div> <label for="firstName">First Name :</label> <input type=" ...

Issue with accessing form in Angular 6 Reactive forms for custom validator functionality

I am facing an issue with creating a password validation for reactive forms in Angular. Every time I try to verify the password, I get a “Cannot read property 'get' of undefined” error in the console. I have tried different methods to access ...

Include a control within a form based on the Observable response

I am looking to enhance my form by adding a control of array type, but I need to wait for the return of an Observable before mapping the values and integrating them into the form. The issue with the current code is that it inserts an empty array control e ...

How to handle type errors when using properties in Vue3 Single File Components with TypeScript

I've hit a roadblock while attempting to utilize properties in Vue3. Despite trying various methods, I keep facing issues during the type-check phase (e.g.: yarn build). The project I'm working on is a fresh Vue3-ts project created using Vite. B ...

Unexpected behavior with onKeyPress in React-Native Windows resulting in missing key press events

Currently, I am working on a Windows app using react-native version 0.54.0. For one of the functionalities, I have incorporated a TextInput element and would like to use onKeyPress. Here is my code snippet: <TextInput ref = { this.setTextInputRef } on ...

Establish a reactive form upon data completion (asynchronously) in Angular version 5

I've been encountering an issue with updating form values post fetching data from an API. I attempted to utilize the *ngIf technique, but unfortunately, the form remains invisible even though it is properly set. Although I cannot provide the entire p ...

Steps to generate an accurate file order using Typescript:

Consider the scenario with two typescript files: In File a.ts: module SomeModule { export class AClass { } } And in File b.ts: module SomeModule { export var aValue = new AClass(); } When compiling them using tsc -out out.js b.ts a.ts, there are ...

What is the best way to save data from a Firebaselistobservable into an array?

I've been attempting to transfer data from Firebase to an array using Angular 2, but I'm facing difficulties in pushing the data into the array. Below is the code snippet: Variables: uid: string = ''; agencyItems: FirebaseListObserva ...

Type of result from a function that returns a linked promise

In my class, I have a method that returns a chained promise. The first promise's type is angular.IPromise<Foo>, and the second promise resolves with type angular.IPromise<Bar>. I am perplexed as to why the return type of doSomething is an ...

In a Next.js project, Typescript seems to be overlooking errors related to proptype definitions and function types

Greetings everyone! I am currently working on a project using TypeScript and have implemented various rules and elements. However, I am facing issues with type errors for functions and props. Essentially, when using any function, it is necessary to specify ...

`In Vue.js, it is not possible to access a data property within a

I encountered an issue while attempting to utilize a property of my data within a computed method in the following manner: data() { return { ToDoItems: [ { id: uniqueId("todo-"), label: "Learn Vue", done: false }, ...

Guide to setting up a trigger/alert to activate every 5 minutes using Angular

limitExceed(params: any) { params.forEach((data: any) => { if (data.humidity === 100) { this.createNotification('warning', data.sensor, false); } else if (data.humidity >= 67 && data.humidity <= 99.99) { ...

Attempting to retrieve a file from the database with the utilization of Angular 5 and ASP.NET Core

I've been struggling with downloading a file from the database using its unique identifier. Can anyone provide guidance on what steps are necessary to achieve this successfully? The FileUpload table contains the following columns pertaining to the fi ...

Translate Typescript into Javascript for use in React applications

Can anyone assist me in converting this Typescript code to Javascript? function ImageMagnifier({ src, width, height, magnifierHeight = 100, magnifieWidth = 100, zoomLevel = 1.5 }: { src: string; width?: string; height?: string; magnifie ...

What is the reason behind Typescript executing the abstract class before anything else?

I'm currently facing a challenge solving an abstract class problem with Typescript. Let me explain what I am trying to accomplish. There is a class named Sword that extends Weapon. Each Weapon must have certain properties like the damage, but since e ...

Techniques for simulating functions in Jest

I have a pair of basic components that I'm currently creating tests for using jest. My goal is to verify that when I click on a currencyItem, the corresponding array gets added to the select state. To achieve this, I am passing the handleCurrencyToggl ...

Effortlessly converting JSON data into TypeScript objects with the help of React-Query and Axios

My server is sending JSON data that looks like this: {"id" : 1, "text_data": "example data"} I am attempting to convert this JSON data into a TypeScript object as shown below: export interface IncomingData { id: number; t ...