Determining the Type of a Variable in TypeScript: Interface or Array of Interface?

After extensive searching online, I have yet to find a suitable solution for my problem. Here is a simplified outline of what I am attempting to achieve:

interface list {
    people: Person | Array<Person>
}

interface officialList {
    people: Array<Person>
}

toOfficialList(list: List): officialList {
    //Seeking method to determine if the list.people consists of a single person or an array of people
    //Function will return an official list, converting "Person" into "[Person]"
}

If a list containing an array of people is inputted, the function will not need to make any changes and can simply return the same list.

However, if the list has only one person in it, the function should convert that individual into an array with one element.

Answer №1

If you have a Person and not an array, you can determine if it is a Person or an Array<Person> by using the Array.isArray() method. Your toOfficialList() function could be written as follows:

function toOfficialList(list: List): OfficialList {
  return { people: Array.isArray(list.people) ? list.people : [list.people] };
}

I hope this solution helps you out. Best of luck!

Click here for code

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 it possible to use null and Infinity interchangeably in JavaScript?

I've declared a default options object with a max set to Infinity: let RANGE_DEFAULT_OPTIONS: any = { min: 0, max: Infinity }; console.log(RANGE_DEFAULT_OPTIONS); // {min: 0, max: null} Surprisingly, when the RANGE_DEFAULT_OPTIONS object is logged, i ...

Injecting AngularJS together with TypeScript and Restangular to optimize application performance

Encountering an issue while trying to configure my angularjs + typescript application with the restangular plugin Here are the steps I have taken: Ran bower install --save restangular (now I have in index.html <script src="bower_components/restang ...

The RXJS subscribe function fails to work when called within an HTML document

I am encountering an issue where an observable is not being invoked from the HTML page. The method works perfectly fine when triggered by angular and displays the desired output. However, when attempting to invoke it through a button, it does not work. ...

transform array of strings to array of integers

Looking to convert a string array ["1","2","3"] into an int array [1,2,3] in C# as quickly as possible - any suggestions? Many thanks! ...

Retrieve data from a database using Angular

I am using Symfony as the Backend and Angular as the Frontend. I am attempting to showcase a list of all users from my postgresql database in a table. However, the browser only displays the information passed within the tags. ![display example](View post ...

Accessing an array in one class and using it in another

I'm currently working on developing a snakes and ladders game. The challenge I'm facing involves integrating two classes: one being the primary GUI displayed in a JFrame, showcasing an image of a snakes and ladders board, and the other comprising ...

The name 'const' is missing or not found

While working on my Angular application, I attempted to utilize the Typescript 3.4 feature known as "const assertion" in the following manner: const counterSettingsDefaults = { setTo: 10, tickSpeed: 200, increment: 1 } as const; Unfortunately, this resul ...

Can you provide guidance on adjusting the dimensions of the Carousel element within the ShadCN UI?

My React component setup currently includes the following: "use client"; import Autoplay from "embla-carousel-autoplay"; import { Card, CardContent } from "@/components/ui/card"; import { Carousel, CarouselContent, ...

Error: The function $.cookie() is not defined in Angular2 Typescript

After installing @types/jquery, I updated tsconfig.json to include jquery.cookie in the types section. Visual Studio Code indicates that $.cookie is ready for use, but when I execute my code, an error appears in the console stating that $.cookie() is not ...

Utilizing PrimeNG dropdowns within various p-tree nodes: Distinguishing between selected choices

I am working with a PrimeNg p-tree component <p-tree [value]="treeNodes" selectionMode="single" [(selection)]="selectedNode"></p-tree> The treeNodes are defined using ng-templates, with one template looking li ...

Unable to locate the reference to the term 'require' in Angular 8

Encountering compilation issues after integrating the fast-image-size node module. Despite attempting several troubleshooting steps, I have been unable to resolve the problem. As a last resort, I included "types": ["ts-node"], in the tsconfig.js file, but ...

Neglectful TypeScript null checks overlooking array.length verification

When TypeScript is compiled with strict null checks, the code snippet below does not pass type checking even though it appears to be correct: const arr: number[] = [1, 2, 3] const f = (n: number) => { } while (arr.length) { f(arr.pop()) } The comp ...

Angular: Unable to locate route declaration in the specified path /src/app/app-routing.module.ts

Whenever I attempt to set up automatic routing for components that have been created using the command below ng generate module orders --route orders --module app.module I encounter the following error message The requested URL /src/app/app-routing.mod ...

Go through every item in the list and update each element of the array with the outcome, doing so concurrently

Currently, I am struggling with implementing array asynchronous iteration functionality. I am working with the node-opcua library in Node.js. Specifically, I am using the function session.browse(nodeId, result). NodesTree = { "NodesTree":{ ...

Angular 5: ngModelChange not triggering API call on bad request

When a user inputs a city name in a text box, I need to check if it is valid by calling the onCityChange() function using ngModelChange. This function emits the user-entered data on an rxjs Subject, which I subscribe to in the ngOnInit() method. Utilizing ...

Is there a way for me to use TypeScript to infer the type of the value returned by Map.get()?

type FuncType<O extends Object> = (option: O) => boolean export const funcMap: Map<string, Function> = new Map() const func1: FuncType<Object> = () => true const func2: FuncType<{prop: number}> = ({ prop }) => prop !== 0 ...

Adjusting the settimeout delay time during its execution

Is there a way to adjust the setTimeout delay time while it is already running? I tried using debounceTime() as an alternative, but I would like to modify the existing delay time instead of creating a new one. In the code snippet provided, the delay is se ...

Using Required and Partial with an Array of Generic Types

I'm currently working with the following types: interface Color { color: string } type DarkerColor<T> = T & Color & { darker: string } type ColorInfo<T> = DarkerColor<T> & { hue: number luminance: number opacity ...

What is preventing TypeScript from resolving assignment in object destructuring?

Consider the code snippet below: interface Foo { a?: number b?: number } function foo(options?: Foo) { const { a, // <-- error here b = a } = (options ?? {}) return [a, b] } Why does this code result in the followi ...

Validating Neighboring Values in a Numpy Array

Currently, I am exploring more efficient methods to identify connected components in an image. My approach involves working with an array containing coordinates and values. The goal is to group these coordinates based on their proximity to each other. At t ...