An assortment of diverse data types in TypeScript arrays

Considering adding type to my existing API, I have a function that can accept a string, function, or object (utilizing overloading). However, it is also able to accept an array of mixed values.

Is there a way to have an Array in TypeScript that consists of strings, functions, or plain objects only, and throws an error for any other types?

UPDATE: In response to feedback, I made the following changes:

function Terminal(interpreter: (string, object) => void, settings: object);
function Terminal(interpreter: (string | ((string, object) => void) | object)[], settings: object) {
    if (typeof interpreter == 'function') {
        interpreter("foo", {});
    } else if (interpreter instanceof Array) {
        interpreter.forEach((arg) => console.log(arg));
    }
}

Terminal(["foo", function (command, term) { }], {});
Terminal(function(command) {

}, {});

However, I encountered an error in the TypeScript playground related to the signature overload not matching the implementation and invocation.

Answer №1

When utilizing a union type, it is essential to enumerate all potential argument types within that union. For instance, if you want a function to accept either a string, a function, or an object, you can create a type alias for a single value that encompasses all these possibilities.

type SingleArg = string | object | ((string, object) => void);

By defining this type alias, you can then create a function that takes either a SingleArg or an array without needing multiple overloads.

function Terminal(interpreter: SingleArg | SingleArg[], settings: object) {
    if (typeof interpreter == 'function') {
        interpreter("foo", {});
    } else if (interpreter instanceof Array) {
        interpreter.forEach((arg) => console.log(arg));
    }
}

Terminal(["foo", function (command, term) { }], {});
Terminal(function(command) {

}, {});

One challenge mentioned is ensuring that the function throws an error when passed an array containing types other than the specified ones. This can be tricky, especially since numbers are treated as objects in TypeScript. To exclude numbers but allow objects, a more precise definition of acceptable object types is required.

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

What is the best way to implement an EventHandler class using TypeScript?

I am in the process of migrating my project from JavaScript to TypeScript and encountering an issue with transitioning a class for managing events. To prevent duplicate option descriptions for adding/removing event listeners, we utilize a wrapper like thi ...

Having trouble with GraphQL Explorer and Express Sessions compatibility?

Struggling to implement a login system using GraphQL and Express, but facing issues with session persistence. Despite logging in, req.session.userId remains undefined. Code snippet: (async () => { await connect(process.env.MONGO_URI!, { dbName: "ex ...

Expanding the Warnings of React.Component

When I create a new class by extending React.Component in the following manner: export default class App extends React.Component<any, any > { constructor (props: React.ReactPropTypes) { super(props); } // other code } I encountere ...

Creating a .d.ts file for a JavaScript file that exports a plain object - tips and best practices

I am attempting to include a .d.ts file for an existing js file. The type.js file looks like this: // type.js export default { NORMAL: '001', CHECK: '002', }; Now, I have added a type.d.ts file as follows: // type.d.ts decla ...

How can I invoke object functions stored in an array using Javascript?

I'm currently attempting to iterate through an array of game objects and invoke their update methods. The challenge is that game objects may have different update implementations - for example, the update function for an enemy is different from that o ...

Using Azure AD for authentication: Implementing Msal authentication in a React Next.js application with TypeScript and App Router

Working on a React Next.js web application with Microsoft Authentication Library (MSAL) login integration, using Azure. The app utilizes Next.js with the App Router for routing. But encountering an error when attempting to run the app: createContext only w ...

In Angular2, declaring variables with log={} and dynamically adding log details like [{id: "Logs List Details1"}, {id: "Logs List Details2"}] is a simple process

When declaring a variable with log = [{id: "Logs List Details1"},{id: "Logs List Details2"},....etc}] dynamically, issues arise when pushing dynamic data to it. If the data is static and pushed incrementally, it exceeds the page limit. However, if only one ...

Utilize Primeng data grid to calculate total sum and display it in the footer section

I have been utilizing primeng datatable in a recent project and am currently facing an issue with calculating the sum in the footer of a row grouping DataTable. The summation needs to occur while data is being edited and new data is being entered. Below i ...

Creating a function that is accessible to the entire module

Creating a universal function in a file that is not a module: example.ts: function example() {} You can easily call this function from another file, say test.ts, without needing to import the function from example.ts: test.ts: example(); // calling univ ...

submitting a collection of hashes to a server using jQuery

I'm facing an issue with sending data to the server. I have an array structured like this: places = new Array(); places.push({name: "ci", loc: "bo"}) places.push({name: "ae", loc: "ea"}) if I try to send this data to the server using the following J ...

Zero-length in Nightmare.js screenshot buffer: an eerie sight

I'm currently working on a nightmare.js script that aims to capture screenshots of multiple elements on a given web page. The initial element is successfully captured, but any subsequent elements below the visible viewport are being captured with a l ...

Wondering how to implement HubSpot Conversations SDK in a Typescript/Angular application?

Recently, I came across some useful javascript code on this website window.HubSpotConversations.widget.load(); window.HubSpotConversations.widget.refresh(); window.HubSpotConversations.widget.open(); window.HubSpotConversations.widget.close(); Now, I am l ...

When performing the operation number.tofixed in Typescript, it will always return a string value instead of a double datatype as expected from parseFloat

let value = 100 value.toFixed(2) -> "100.00" parseFloat(value.toFixed(2)) -> 100 I am encountering an unexpected result with the double type when input is 100.36, but not with 100.00. Framework: loopback4 ...

React modal not closing when clicking outside the modal in Bootstrap

I recently utilized a react-bootstrap modal to display notifications in my React project. While the modal functions correctly, I encountered an issue where it would not close when clicking outside of the modal. Here is the code for the modal: import Reac ...

Ways to customize the OverridableComponent interface within Material-UI

Is there a way to effectively use the Container component with styled-components incorporating ContainerProps, while still being able to pass the component prop that belongs to the OverridableComponent interface? Currently, I am encountering an error when ...

Selling beyond webpack's confines

Today I had an interesting thought and couldn't find much information on it, so I decided to share some strange cases and how I personally resolved them (if you have a better solution, please feel free to comment, but in the meantime, this might be he ...

Tips for expanding interfaces/classes during variable declaration

Is it possible to extend an interface or class during variable declaration? For instance: export declare abstract class DynamicFormControlModel implements DynamicPathable { asyncValidators: DynamicValidatorsConfig | null; _disabled: boolean; ...

"Encountering an issue with opening a form in a child component from the parent - receiving an error message 'unable to access

Here's the scenario: I am working with a list of companies that each have an array of projects as one of their variables. The desired functionality is to display the list of companies in the parent component/html, and only open a child component to sh ...

What is the best way to substitute NaN values in an array with the closest succeeding number?

In order to address my dilemma with accuracy, allow me to provide more detail. I am collecting a significant amount of data from an experiment and storing it in two arrays: count and tick. These arrays are then utilized to compute the value of factor using ...

Packaging a NodeJS project in Visual Studio - A step-by-step guide to creating and setting up an N

In my VS2013 solution, I have a combination of NodeJS (using TypeScript) and C# class library projects connected by EdgeJS. Among the NodeJS projects, one serves as a library for a RabbitMQ bus implementation, while two are applications meant to be hosted ...