Improved method for verifying Array<any> data type

To address my primary issue, I am seeking a way to specifically detect when a type is Array<any>, excluding any other array types.

I have found that this can be achieved by combining two conditions: T extends Array<any> and Array<any> extends

Is there a method for creating a conditional type without having to rely on a dual ternary operation like the one shown below:

type foo<T> = T extends Array<any> ? Array<any> extends T ? T : 'not any array' : 'not any array';

Answer №1

Here's a clever method that only requires one conditional type, inspired by the technique in this post:

type foo<T> = [1[] & T, any[]] extends [0[], T] ? T : "not any array";

This code contains two checks: one to verify if it's an any[], and another to prevent never[]. By leveraging the behavior of any, we can identify arrays. However, this approach also allows never[] to pass through.

To handle never[], we implement an additional check. Since never is the bottom type with no assignable values, confirming if any[] can be assigned to

T</code covers all cases.</p>
<p>Try out these test examples:</p>
<pre><code>type T01 = foo<any[]>
//   ^? any[]
type T02 = foo<never[]>
//   ^? "not any array"
type T03 = foo<number[]>
//   ^? "not any array"
type T04 = foo<{ bar: any }>
//   ^? "not any array"
type T05 = foo<{ 1: any }>;
//   ^? "not any array"

Check it out here

Answer №2

Let me share with you a way to achieve what I think you are aiming for (please let me know if there are any corrections needed)

type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N;
type IfAnyArray<T, Y, N> = T extends ReadonlyArray<infer V> ? IfAny<V, Y, N> : N;
type IsAnyArray<T> = IfAnyArray<T, 'is any[]', 'is not any[]'>


type test_fooz = IsAnyArray<(number | string)[]>
//   ^?
type test_foo0 = IsAnyArray<number[] | string[]>
//   ^?
type test_foo1 = IsAnyArray<string[]>
//   ^?
type test_foo2 = IsAnyArray<any[]>
//   ^?
type test_foo3 = IsAnyArray<readonly string[]>
//   ^?
type test_foo4 = IsAnyArray<readonly any[]>
//   ^?
type test_foo5 = IsAnyArray<MyArray<string>>
//   ^?
type test_foo6 = IsAnyArray<MyArray<any>>
//   ^?
type test_excb = IsAnyArray<(string & {brand: 'myBrand'})[]>
//   ^?
type test_excB = IsAnyArray<(string & {brand?: 'myBrand'})[]>
//   ^?


class MyArray<T> extends Array<T> {
    x!: number;
}

If you're looking into using Exclude, here's how:

type ExcludeArrayOf<T, E> = T extends ReadonlyArray<infer V extends E> ? IfAny<V, T, never> : T;
 
type test_excz = ExcludeArrayOf<(number | string)[], string>
//   ^?
type test_exc0 = ExcludeArrayOf<number[] | string[], string>
//   ^?
type test_exc1 = ExcludeArrayOf<string[], string>
//   ^?
type test_exc2 = ExcludeArrayOf<any[], string>
//   ^?
type test_exc3 = ExcludeArrayOf<readonly string[], string>
//   ^?
type test_exc4 = ExcludeArrayOf<readonly any[], string>
//   ^?
type test_exc5 = ExcludeArrayOf<MyArray<string>, string>
//   ^?
type test_exc6 = ExcludeArrayOf<MyArray<any>, string>
//   ^?
type test_excb = ExcludeArrayOf<(string & {brand: 'myBrand'})[], string>
//   ^?
type test_excB = ExcludeArrayOf<(string & {brand?: 'myBrand'})[], string>
//   ^?

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

Retrieve the list of users playing certain games using the start.gg API

Is there a way to retrieve all users from Smash Ultimate using the start.gg API? I couldn't find any information about fetching all users, only details about tournaments or specific player sets. You can access the API here: Thank you in advance for ...

The NgZone reference error caused the prerendering to fail

I am facing challenges with the implementation of NgZones. Despite defining NgZone, I keep encountering this error: "NodeInvocationException: Prerendering failed because of error: ReferenceError: NgZone is not defined" Below is my app.error-handle.ts file ...

Encountering a problem with an InvalidPipeArgument in Angular 6

Here's a quick summary of the situation: I recently upgraded my application to the latest version of Angular, moving from 5 to 6. All deployments in the packages.json file were updated using the ng update command. In my application, I save a Date() ...

The property functions normally outside the promise, but is undefined when within the promise context

I am currently working on filtering an array based on another array of different objects but with the same key field. Although I have made some progress, I keep encountering errors that I am unable to resolve. @Component({ selector: 'equipment&ap ...

Ways to implement a filter pipe on a property within an array of objects with an unspecified value

Currently, I'm tackling a project in Angular 8 and my data consists of an array of objects with various values: let studentArray = [ { Name: 'Anu', Mark: 50, IsPassed: true }, { Name: 'Raj', Mark: 20, IsPassed: false }, { Na ...

What is the process for adding my Ionic app to the share menu on an iPhone?

I'm working on an Ionic 3 app and I want it to be integrated into the iPhone share list just like shown in this example, https://i.sstatic.net/U2Lqr.png The Share option should appear when users access the gallery and then when they press the share b ...

Trying to add an item to a TypeScript nested array causes an issue: unable to access property 'push' because it is undefined

For a while now, I've been searching on SO trying to find a solution to my issue. It seems that my code isn't as simple as just "push object into array." In my interface, I have a "Year" property typed with another interface as an array: exp ...

Tips for utilizing regex to locate words and spaces within a text?

I'm feeling so frustrated and lost right now. Any help you can offer would be greatly appreciated. I am currently dealing with an issue in Katex and Guppy keyboard. My goal is to create a regex that will identify the word matrix, locate the slash that ...

Eliminate the hashtag (#) from the URL in Angular 11

I am facing an issue with removing the # from the URL. When I try to remove it, the application encounters a problem upon deployment to the server. Upon page refresh, a 404 error status is returned. For instance: https://example.com/user/1 (works) https ...

Issues with Tagged Union Types in Visual Studio Code

Currently, I am working on implementing a tagged union type pattern for my action creators within a redux application. The TypeScript compiles without any issues, however, my code editor, Visual Studio Code 1.26.1, is flagging an error. [ts] Type &ap ...

Importing TweenLite in Typescript is a breeze

After downloading the GSAP package via npm, I am keen on importing the TweenLite class to my TypeScript app. While importing all of GSAP can be achieved by using require('gsap'); and it functions correctly, this method does not work in TypeScript ...

Angular 2 feature that allows for a single list value to be toggled with the

Currently, my form is connected to a C# API that displays a list of entries. I am trying to implement a feature where two out of three fields can be edited for each line by clicking a button that toggles between Yes and No. When the button is clicked, it s ...

The various types of Angular 2 FormBuilders

As I delved into learning Angular 2, I initially came across ngModel, and later discovered FormGroup/FormBuilder which seemed more suitable for handling complex forms. However, one downside that caught my attention was that by using FormBuilder, we sacrifi ...

Using routerLink for linking to multiple components

Below is the anchor tag provided: <a class="uppercase" routerLink="settings/pressure" routerLinkActive="text-success" (click)="closeModal()" > <div class="pad-btm"> PRESSURE </div> </a> I need to include another route ...

Tips for efficiently handling large Excel files in NodeJS without freezing the user interface

Currently, my NodeJS/Angular/Electron app is utilizing the ExcelJS library to read large Excel files that contain over 10,000 lines. While smaller files are processed smoothly, larger files take between 3.9 and 5 seconds to load, during which time the CSS ...

Secure your NetSuite API calls with OAuth 1.0 signature authorization

After extensively reviewing the documentation and various posts on Stack Overflow about creating a signature for NetSuite OAuth1.0 with TBA, I believe that I have followed all of the necessary steps and correctly generated the key. However, upon making the ...

What is the best way to run Jest tests only from a particular folder without including tests from other folders?

My node js project has 2 test folders: app and admin, both located inside the src/test/v1 directory. I am looking for a script that will run tests only from the app folder. I have attempted running tests using "jest app" and "jest app --testPathPattern=s ...

Incorrect conditions when attempting to compare text strings

My current code retrieves the user's locale and saves it in a variable. I have implemented a conditional statement that checks if the locale matches a specific value - as shown in the image below: https://i.sstatic.net/ASVZ8.png In the screenshot, y ...

What's the trick to aligning the label on the material-ui text field to the right side?

I am working on a React project with an RTL layout using material-ui and typescript. I am struggling to align the label of a text field to the right. Can anyone help me with this? https://i.sstatic.net/UrkIF.jpg ...

Identifying whether a particular area is represented in a geographic map array presents a significant challenge

Having an issue with typescript currently. I have a variable that contains different string entries representing x, y positions. The entries are as follows: ["3,3","3,4","3,5","2,3","2,4","2,5","-1,-2","-2,- 2","-2,-1"] My goal is to determine if this land ...