Creating a type that can be used with a generic type T along with an array of the same generic type T

I am experimenting with TypeScript for this project

type ArrayOrSingleType<T> = T | T[];

interface TestType<T> {
    a: ArrayOrSingleType<T>;
    b: (v: ArrayOrSingleType<T>) => void;
}


const testVariable: TestType<number> = {
    a: 4,
    b: (v) => console.log(v)
}

testVariable.b([2]);

Now, I aim to maintain consistency so that testVariable.b([2]) triggers an error due to the fact that a is a singular number, not an array of numbers

After seeking help from ChatGPT, I received a solution:

type ArrayOrSingleType<T> = T extends any[] ? T[] : T;

interface NewTestType<T, U extends ArrayOrSingleType<T>> {
    a: U;
    b: (v: U) => void;
}

// This will generate an error
const example1: NewTestType<number, number> = {
    a: 4,
    b: (v: number[]) => console.log(v) // Error: 'v' should be a single number, not an array of numbers
}

// This one is correct
const example2: NewTestType<number, number[]> = {
    a: [4],
    b: (v: number[]) => console.log(v) // 'v' should be an array of numbers
}

However, I desire a solution where I can avoid specifying the type twice (e.g.,

const example2: NewTestType<number, number[]> = {
. I want to be able to declare
const example2: NewTestType<number> = {

Answer №1

The solution presented here closely resembles the approach taken by GPT.

type ArrayOrSingle<T> = T extends any[] ? T[] : T;

interface Test<T extends ArrayOrSingle<unknown>> {
    a: T;
    b: (v: T) => void;
}

// An error should be thrown for this case
const t1: Test<number> = {
    a: 4,
    b: (v: number[]) => console.log(v) // Error: 'v' should be a number, not number[]
}

// This case should work without errors
const t2: Test<number[]> = {
    a: [4],
    b: (v: number[]) => console.log(v) // 'v' should be a number array
}

Explore the Live Playground here

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

Is there a way to change an ISO 8601 date into the format '/Date(1525687010053)/' using JavaScript?

Is there a way to convert a date value that is formatted as 9999-12-31T00:00:00Z to the format /Date(1525687010053)/ using javascript? I tried implementing the following code, but it doesn't seem to be working: var datevalue = '9999-12-31T00:00 ...

Update your mappings for the city of Istanbul when utilizing both TypeScript and Babel

Currently, I am facing the challenge of generating code coverage for my TypeScript project using remap Istanbul. The issue arises due to the usage of async/await in my code, which TypeScript cannot transpile into ES5 directly. To circumvent this limitation ...

The property of the Angular Typescript object is distinctly not defined, yet the property itself is

Currently facing a bizarre issue. Even though the console displays data in an object from a subscribed observable, TypeScript code shows it as undefined. Take a look: initData(): void { this.backendService.getData().subscribe((depotDays: DepotDayAcc ...

NextJS and Context API throwing a Typescript error

I've been working on my _app.tsx file and here's the code snippet I have: import React from 'react' import type { AppProps } from 'next/app' /* Import Styles */ import '@themes/index.scss' /* Import Template */ imp ...

Saving in prettier differs from running it with npm

./file.ts (INCORRECT) import { jwtGroupClaimToRolesDomain, ScopeIds } from '@invison/shared'; import { Injectable, NestMiddleware } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Response } fro ...

How to implement angular 2 ngIf with observables?

My service is simple - it fetches either a 200 or 401 status code from the api/authenticate URL. auth.service.ts @Injectable() export class AuthService { constructor(private http: Http) { } authenticateUser(): Observable<any> { ...

Ways to display an error message in Angular 8 when entering anything other than numbers in a text box

In my Angular 8 application, I have a text box that only allows the user to type numbers. If they try to type an alphabet or special character, it should display an error message below the text box. The error message should disappear once the user starts ...

Remove the package from the @types folder within the node_modules directory

I currently have the 'mime' library in my node_modules directory and I am looking to completely remove it from my project, along with its @types files. The reason for this is that the old mime package is not functioning correctly for me, so I wan ...

Establish a route nickname for files outside the project directory

I'm currently tackling a project that is divided into multiple angular projects. Within these projects, there are some services that are shared. Is there a way for me to incorporate these services into my project without encountering errors? /root / ...

Ways to avoid Next.js from creating a singleton class/object multiple times

I developed a unique analytics tool that looks like this: class Analytics { data: Record<string, IData>; constructor() { this.data = {}; } setPaths(identifier: string) { if (!this.data[identifier]) this.da ...

Combine various arrays of objects into one consolidated object

Problem: There are untyped objects returned with over 100 different possible keys. I aim to restructure all error objects, regardless of type, into a singular object. const data = [ { "type":"cat", "errors" ...

Visibility of Input-properties in Angular 2

I am encountering an issue where a component parent is calling another component child with an input-property. Although the property is available in the child's template, it does not seem to be accessible within the constructor or OnInit functions. I ...

Prisma Remix is throwing a TypeError: "The function (0, import_prisma.createNote) is not defined as a function."

In my project, I wrote a function using the prisma client which is being called from the notes.tsx route in remix. export async function createNote(entity: { title: string, description: string }) { const note = await prisma.note.create({ data: ...

What is the reason for not hashing the password in this system?

My password hashing code using Argon2 is shown below: import { ForbiddenException, Injectable } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { AuthDto } from './dto'; import * as arg ...

Determine rest parameters based on the initial argument

Struggling to generate a solution that infers the arguments for an ErrorMessage based on the provided code input. ./errorCodes.ts export enum ErrorCodes { ErrorCode1, ErrorCode2, ErrorCode3 } ./errorMessages.ts export const ErrorMessages = { [Err ...

Adjusting the angular routerLink based on an observable

When working with HTML in Angular, I am looking for a way to use an <a> tag that adjusts its routerlink based on whether or not a user is logged in. Is it possible to achieve this functionality within a single tag? <a *ngIf="!(accountService ...

Launching the Skeleton feature in NextJS with React integration

I have been working on fetching a set of video links from an Amazon S3 bucket and displaying them in a video player component called HoverVideoPlayer. However, during the loading process, multiple images/videos scale up inside a Tailwind grid component, ca ...

What is the best way to execute TypeScript programs on an Android device?

Is there a way to execute TypeScript programs on an Android phone? Are there any offline apps specifically designed for running TypeScript programs on Android devices? ...

Issues are arising with Angular Form where the FormControl is not being properly set up for the first field in my form

After grappling with this issue for several weeks, I am still unable to pinpoint the cause. (Angular version: 16.1.4) The form component is populated using a BehaviorSubject, and although the console prints out the correct values for both the form and dat ...

Can the garbage collector in Typescript/JavaScript effectively handle circular references, or does it result in memory leaks?

When working in languages such as C#, managing memory is not a problem. However, this can lead to difficult-to-find memory bugs in other languages. Is it safe to use the following code snippet in Typescript or Javascript without encountering any issues? c ...