TypeScript has two variable types

I'm facing a challenge with a function parameter that can accept either a string or an array of strings. The issue arises when trying to pass this parameter to a toaster service, which only accepts the string type. As a result, when using join(' '), I encounter an error message:

Property 'join' does not exist on type 'string | string[]'. Property 'join' does not exist on type 'string'.
This prevents the application from compiling successfully.

showToaster(msg: string, customClass: string | string[]) {
        let cstmClass: any;

        switch (typeof customClass) {
            case 'string':
                cstmClass = customClass;
                break;
            case 'object':
                cstmClass = customClass.join(' ');
                break;
        }

        this.toastrService.show(msg, null, {
            toastClass: cstmClass,
            timeOut: 3500
        });
}

Answer №1

To identify the type, it is recommended to utilize Array.isArray:

if(Array.isArray(customClass)) {
    cstmClass = customClass.join(' ');
}
else {
    cstmClass = customClass;
}

The rationale behind using an array for compilation is that the | option exclusively shows properties and methods common to both types. Checking if the type is an object is not sufficient due to the absence of a join method in the generic object.

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

Utilize the CSS class or variable within an Angular TypeScript file for enhanced styling and functionality

Is it possible to utilize the scss class or variable in a typescript file? scss .thisIsGreen { color: green; } .thisIsBlue { color: blue; } Alternatively, you can use $thisIsGreen { color: green; } $thisIsBlue { color: blue; } Now, I want to ...

Searching for evenly distributed GPS coordinates across an area

I have a collection of data points representing mountain peaks in the European Alps that I would like to showcase on a map. To prevent cluttering the user interface, I currently retrieve the highest peaks within the visible area of the map by sorting them ...

Tips for utilizing mergeWith with Subjects in an Angular application

Objective: Creating a Combined Filter with 3 Inputs to refine a list Conditions: Users are not required to complete all filters before submission The first submit occurs when the user inputs data Inputs are combined after more than one is provided Appro ...

Utilizing Fullcalendar 5 in conjunction with Angular: Embedding Components within Events

Recently, my team made the transition from AngularJS to Angular 12. With this change, I upgraded Fullcalendar from version 3 to version 5 and started using the Angular implementation of Fullcalendar: https://fullcalendar.io/docs/angular While navigating t ...

Can ngFor be utilized within select elements in Angular?

I'm facing an interesting challenge where I need to display multiple select tags with multiple options each, resulting in a data structure that consists of an array of arrays of objects. <div class="form-group row" *ngIf="myData"> <selec ...

Using Handlebars.js with Angular CLI versions 6 and above: A Step-by-Step Guide

Looking to create a customizable customer letter in either plain text or HTML format that can be edited further by the customer. Considering using Handlebars.js to render an HTML template with mustache tags, using a JSON object for business information. T ...

The potential for an 'undefined' object in TypeScript React is a concern that should be addressed

Currently, I am honing my skills in using TypeScript with React and retrieving data from an API that I set up a few days back. The API is functioning properly as I am able to fetch data for my front-end without any issues. However, when I attempt to util ...

Empty initial value for first item in array using React hooks

My goal is to store an array that I retrieve from an API in a useState hook, but the first entry in my array always ends up empty. The initial array looks like this: (3) ["", "5ea5d29230778c1cd47e02dd", "5ea5d2f430778c1cd47e02de"] The actual data I recei ...

Implement a T3 App Redirect in a TRPC middleware for unsigned users

Is there a way to implement a server-side redirect if a user who is signed in has not finished filling out their profile page? const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { if (!ctx.session || !ctx.session.user) { throw new TRPCE ...

Troubleshooting issue with loading local json files in Ionic 3 on Android device

Recently, I've been exploring the process of loading a local JSON data file in my project. I have stored my .json files in the /src/assets/data directory and here is the provider code snippet that I am utilizing: import { Injectable } from '@ang ...

Explain what one-time typescript interfaces are

As someone who has been using React for quite some time, I am now looking to integrate Typescript into my projects. In the past, I would create large "container" objects like this: const theme = { colors: { primary: '#00f', accent: &ap ...

Tips for utilizing the 'crypto' module within Angular2?

After running the command for module installation: npm install --save crypto I attempted to import it into my component like this: import { createHmac } from "crypto"; However, I encountered the following error: ERROR in -------------- (4,28): Canno ...

Using an Angular interface for an HTTP request: The statusText message reads as "Error: Unable to Determine."

I've been working on calling an API as an example in Angular using an interface. The API I'm trying to access is located at https://jsonplaceholder.typicode.com/posts. Unfortunately, I encountered the following error message: ERROR HttpErrorResp ...

Ways to enable Urql (typescript) to accept Vue reactive variables for queries generated using graphql-codegen

I'm currently developing a Vue project that involves using urql and graphql-codegen. When utilizing useQuery() in urql, it allows for the use of Vue reactive variables to make the query reactive and update accordingly when the variables change. The ...

Identifying row expansion in ngx-datatable: detecting expand status on row click

Is there a way to determine if a line has already been expanded when using the toggle feature? When you click on a line, it expands and shows the details. Here is some code in HTML: <ngx-datatable #dataTable ... (select)='onRowSelect($eve ...

Do we need to import Vue in every component when using Nuxt with TypeScript?

I recently integrated TypeScript into Nuxt using the guidelines provided in the documentation: However, I have a specific question regarding component setup. Should I always include import vue from "vue" and export default Vue.extend ({}); in al ...

Mastering the TypeScript syntax for executing the MongoDB find method

Having trouble properly typing the find method of MongoDB in my TypeScript project that involves MongoDB. Here's the snippet I'm working on: import { ReitsType } from '@/app/api/types/reits'; import { NextRequest, NextResponse } from &a ...

Creating a unique custom selector with TypeScript that supports both Nodelist and Element types

I am looking to create a custom find selector instead of relying on standard javascript querySelector tags. To achieve this, I have extended the Element type with my own function called addClass(). However, I encountered an issue where querySelectorAll ret ...

Ways to utilize array reduce for organizing information

Can someone please guide me on how to use the reduce array method to sort entries by date in the following data: const entries = [ {date: 'lu'}, {date: 'lu'}, {date: 'ma'}, {date: 'ma'} ] I would like the ou ...

Interface-derived properties

One of the challenges I'm facing is dealing with a time interval encapsulation interface in TypeScript: export interface TimeBased { start_time: Date; end_time: Date; duration_in_hours: number; } To implement this interface, I've created ...