Universal interface for objects and arrays

In my Typescript function, I have an argument that can either be an array of strings or a custom object.

The prototype of the function is as follows:

export const myFunction = async (line: string[] | myCustomType, config: any): Promise<String> => {
  if (line?.length < 2)
    //line is a string[]
  else
   //line is a myCustomType
}

Here, myCustomType refers to a raw object with numerous properties and methods.

In JavaScript, I could easily check for line?.length being undefined and treat it as an instance of myCustomType because myCustomType does not have a length property.

Considering an array as an object, I have created a method in the Object class to differentiate between the two types:

declare global {
  interface Object {
    isCustom(): boolean;
  }
}

Object.prototype.isCustom = function () {
  return false;
};

The isCustom method already exists in the myCustomType, but TypeScript does not allow me to compile due to the error message:

Property 'length' does not exist on type 'string[] | myCustomType'.
  Property 'length' does not exist on type 'myCustomType'

Should I declare the type of line as Object and utilize the isCustom() method? Or is there a better solution to this issue?

Any suggestions on how to resolve this problem?

Answer №1

The correct approach is to verify

let isStringArray = false;
if (Array.isArray(data)) {
    isStringArray = true;
    data.forEach(function(element) {
        if (typeof element !== "string") {
            isStringArray = false;
        }
    });
}

Explanation: It is crucial to confirm whether the variable is an array and then determine if all its elements are strings. Relying solely on the length property for validation is flawed, as a custom object could potentially have a length property even if it is not an array. Additionally, a string array may consist of just one or zero elements and still be considered valid.

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

Differentiating between 'TS7030: Not all code paths return a value' and the conflict resolution of ESLint rules 'no-undefined' and 'no-useless return'

Objective I recognize that ESLint is not the ultimate authority and can be customized differently. However, in this query, I am seeking one of the following outcomes: Resolve the conflict while adhering to all specified rules Be advised to disable the ES ...

Utilizing React Native Camera Kit allows for the seamless and continuous scanning of QR codes, offering multiple callbacks when a code is

Attempting to integrate a QR code scanner into my project using react native. Utilizing the plugin react-native-camera-kit, which supports both QR and Bar code scanning. However, I am facing an issue where the scanner continuously scans the code and trig ...

Can you explain the significance of the colon in this context?

Upon reviewing some SearchKit code snippets (composed with react/jsx and es2015), I came across the following line in a jsx file: const source:any = _.extend({}, result._source, result.highlight) I am curious about the purpose or significance of the colo ...

A TypeScript Class that Refers to Itself

I need help with representing a JSON object in an Angular2 typescript class. The JSON object contains an array of objects of its own type. Here is what the JSON object looks like: { "data": { "id": 5, "type": "taxons", "attributes": { ...

Analyzing a string using an alternative character

I want to convert the string "451:45" into a proper number. The desired output is 451.45. Any help would be appreciated! ...

Converting an HTMLElement to a Node in Typescript

Is there a method to transform an HTMLElement into a Node element? As indicated in this response (), an Element is one specific type of node... However, I am unable to locate a process for conversion. I specifically require a Node element in order to inp ...

Is it possible to use a single type predicate for multiple variables in order to achieve type inference?

Is there a way to optimize the repeated calls in this code snippet by applying a map to a type predicate so that TSC can still recognize A and B as iterables (which Sets are)? if(isSet(A) && isSet(B)) { ...

"Sorry, but window.print function is not available in this environment

Whenever I try to execute something in jest, I keep encountering the same error message: console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29 Error: Not implemented: window.alert at module.expor ...

What is the process for implementing a type hint for a custom Chai assertion?

As part of my typescript project, I decided to create a custom assertion for the chai assertion library. Here is how I implemented it: // ./tests/assertions/assertTimestamp.ts import moment = require("moment"); import {Moment} from "moment"; const {Asser ...

Create a visual representation after inserting

I have created an input feature that allows me to paste images by using CTRL-V. The process involves copying an image from the browser and pasting it into the input field using CTRL-V. The result is an image in base64 format. Is there a way to manipulate ...

Learn how to automatically access keys in local storage using Angular

I need to implement a way to store data in local storage so that it persists even when the page is refreshed. In my HTML file, there is a button that triggers a function in my TypeScript file. This function takes a parameter 'game', which is an i ...

How to implement an instance method within a Typescript class for a Node.js application

I am encountering an issue with a callback function in my Typescript project. The problem arises when I try to implement the same functionality in a Node project using Typescript. It seems that when referencing 'this' in Node, it no longer points ...

Is there a way to create numerous div elements in real-time when a click event occurs?

I've created a web application that requires the user to input a product number. Adjacent to the input field is an arrow icon that the user clicks. Upon clicking, there is validation to ensure that the entered number matches one of the valid product n ...

Retrieve an instance of the property class within a property decorator

I'm attempting to create a decorator called @Prop that will assist me in adjusting attributes for custom elements. This is the desired code: class MyCustomClass extends HtmlElement { get content() { return this.getAttribute('content&apo ...

Setting the response type to text in Angular 6 when making an http call

Attempting to send an HTTP request to the Spring REST API, which returns a string value ('success' or 'fail'). However, I am uncertain of how to specify the response type as a string value when making the call to the API. The error mess ...

The 'job' field is not recognized within the 'PrismaClient' type, please check the documentation for correct usage

Currently, I am utilizing Expressjs as a backend along with Prisma for database management and TypeScript implementation. I have been referencing this specific article in my development process. A type error that I am encountering is stated as Property &a ...

Navigating to a different page in Ionic 2 upon app initialization

Is there a way to automatically redirect the page to the home page instead of displaying the login page if there is already a token stored in localStorage? I currently have the following code in the constructor() of app.component.ts, but it still display ...

There seems to be a contradiction in my code - I am returning a Promise but TypeScript is throwing an error saying that the

I currently have a function that retrieves a bot's inventory on the Frontend fetchBotInventory() { this.socket.emit('fetch bot inv'); this.socket.on('bot inv', (botInventory) => { return new Promise((resolve, re ...

Encountering an issue: JwPagination in angular 9 throws an error of "Cannot read property 'currentValue' of undefined"

Currently using Jw pagination with a page size that changes on 5, 10, or 15 using a dropdown. The Angular version being used is angular 9. The HTML code snippet for this functionality looks like: <div class="col-md-6"> <div ...

Error message: The ofType method from Angular Redux was not found

Recently, I came across an old tutorial on Redux-Firebase-Angular Authentication. In the tutorial, there is a confusing function that caught my attention: The code snippet in question involves importing Actions from @ngrx/effects and other dependencies to ...