Is it possible to utilize an @Input() in Angular with multiple types?

Is it possible for a parent component to pass an object in @Input to the child component that may not always be the same? For instance, can I use:

@Input() obj: string | number;

In my scenario, I have two different objects as potential inputs:

@Input() obj: AppDetail | AbsDetail;

Would this configuration work?

Answer №1

Based on your feedback, it seems like you are encountering challenges when dealing with fields that do not overlap in the types. There are a few strategies to address this:

  1. Consider using an @Input for each distinct type. However, I understand that this may not directly answer your question :)

  2. You can utilize & instead of | for your @Input type:

@Input() obj: AppDetail & AbsDetail;

This method offers a quick solution but may not be the most type-safe option, so proceed with caution. It essentially performs an intersect operation on your type objects

  1. You can explicitly define the type before proceeding with your code. For instance:
interface AppDetail {
  id: string;
  details: string;
}

interface AbsDetail {
  code: number;
  details: string;
}

function isAppDetail(obj: AppDetail | AbsDetail): obj is AppDetail {
  return obj.hasOwnProperty('id');
}

function isABsDetail(obj: AppDetail | AbsDetail): obj is isABsDetail {
  return obj.hasOwnProperty('code');
}

@Component({/*...*/})
export class DetailComponent {
  @Input() obj: AppDetail | AbsDetail;

  doSomethingWithObj(): void {
    if (isAppDetail(obj)) {
      // You can now access obj.id without any TypeScript errors
    } else {
      // You have access to obj.code without any issues since it's AbsDetail and the compiler recognizes it as such.
    }
  }
}

Answer №2

checkType(){
if(obj is AppDetail){
    return 1
}

if(obj is AbsDetail ){
    return 2
}
}

I trust this provides clarity.

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 restrict a mapped type in typescript to only allow string keys?

In the Typescript documentation, I learned about creating a mapped type to restrict keys to those of a specific type: type OptionsFlags<Type> = { [K in keyof Type]: boolean; }; If I want to use a generic type that only accepts strings as values: t ...

Discovering the functionality of es6 object.assign and find methods within a typescript file

Currently, I am in the process of transitioning from Java Script to TypeScript for my project. However, I am facing limitations as I am unable to utilize object.assign() and find methods. ...

Error encountered while running npm build: Typescript issue within plotly.js/index.d.ts

Trying to implement this code snippet: import createPlotlyComponent from 'react-plotly.js/factory'; const Plot = createPlotlyComponent(window.Plotly); in my React project implemented in TypeScript. Encountered a TypeScript error during npm run ...

What is the reason for my algorithm's inability to work with this specific number?

I'm currently working on creating an algorithm to compute the sum of prime numbers that are less than or equal to a specified number. Below is my attempt: function calculatePrimeSum(num) { // initialize an array with numbers up to the given num let ...

Unable to retrieve data following a promise in Ionic 3

Hello, I'm currently working on an Ionic application that needs to display data in a Form Group after retrieving it with a SOAP ReadData request. Although I call my function and try to display the data in the form, there seems to be an issue as the f ...

gyp ERROR: Npm encounters difficulty in obtaining a local issuer certificate

I recently did a fresh installation of Windows 10, keeping it clean except for adding cygwin to access Unix commands in the command prompt. During my attempt to install @angular/cli with the command npm install -g @angular/cli, I encountered an error afte ...

Utilizing the filter feature in MatTable

Is there a way to apply an 'or' filter on a MatTable? For instance, I have two independent search fields and want to filter the data if it matches either of them. Can this functionality be achieved by default or would I need to create a custom fi ...

Best Practices for Integrating Angular with Your Custom JavaScript Library

Imagine needing to create a TypeScript function that can be utilized across various components, services, or modules. For example, let's say you want an alert wrapper like this: my_alert(msg); // function my_alert(msg) { alert(msg); } You might hav ...

Is it possible to integrate the Firestore npm library into my Express application?

Recently, I created my own library to act as a nosql database on my node.js web server in place of mongodb. I came across this interesting quote: Applications that use Google's Server SDKs should not be used in end-user environments, such as on pho ...

Removing a targeted element from an array in Angular

After receiving a JSON array object in Angular using TypeScript, I am attempting to remove a specified object from it. However, my attempts at deletion have been unsuccessful. addCategorySub(categorySub: CategorySubModel, index: number) { categorySub.id ...

Bringing in TypeScript declarations for the compiled JavaScript librarybundle

I have a custom library written in TypeScript with multiple files and an index.ts file that handles all the exports. To consolidate the library, I used webpack to compile it into a single index.js file but now I'm facing challenges importing it with ...

How can I incorporate percentage values into input text in Angular?

How can I include a percent sign in an input field using Angular, without relying on jQuery? I am looking for a solution that is identical to what I would achieve with jQuery. Here is the current status of my project: ...

Angularjs and Angular (5) routing combo

I'm currently exploring the possibility of running angular alongside our existing angularjs application. Instead of immediately diving into the tedious process of transitioning to ngUpgrade, I wanted to attempt running them independently first. My ide ...

Adjustable Material UI Switch that reflects the value, yet remains changeable

I am facing a challenge with integrating a Material UI switch (using Typescript) to showcase a status value (active/inactive) on my edit page, and making it toggleable to change the status. I have been able to either display the value through the switch OR ...

The loading of woff2, woff, and ttf files resulted in a 400 error

Can you explain why the woff2, woff, and ttf files in the "assets" folder are not loading? Any suggestions on how to fix this issue? ...

What is the process for transferring data processed in Python to Node.js and then forwarding it to Angular?

I am a newcomer to Angular and I'm looking for a way to showcase JSON data from Python in my Angular app using Node.js. I have already utilized child processes to establish the connection between Python and Node.js, but I am facing a challenge on how ...

Updating a subscribed observable does not occur when pushing or nexting a value from an observable subject

Help needed! I've created a simple example that should be working, but unfortunately it's not :( My onClick() function doesn't seem to trigger the console.log as expected. Can someone help me figure out what I'm doing wrong? @Component ...

Adding a unique prefix for Angular2 routes in various environments

Imagine you are working on an Angular2 application in the development phase, and it is currently running smoothly on localhost:3000. All the routes are functioning properly. However, for deployment on myserver.com/myapp/, you need to add a prefix of myapp ...

The designated apiUser.json file could not be located within the _http.get() function

It's puzzling why my URL isn't working in _http.get('app/api/apiUsers') for Angular version 4.0.0, when it functions correctly in Angular version 2.3.1. The code is identical in both Angular versions: import { Injectable } from ' ...

Typescript libraries built specifically for unique custom classes

I am currently exploring the most effective method for creating a class library in Typescript and deploying it to NPM along with a definitions file. The classes within the library serve as models that are utilized by multiple RESTful services. Some of the ...