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 causes @typescript-eslint to retain old types/files in its cache and prevent successful compilation?

When I kick off my Typescript application using tsc -b -w, I always encounter an issue with @typescript-eslint not reacting to file changes accurately. It flags invalid types/syntax errors where there are none. Restarting the process sometimes doesn't ...

What is a more efficient way to differentiate a group of interfaces using an object map instead of using a switch statement?

As someone still getting the hang of advanced typescript concepts, I appreciate your patience. In my various projects, I utilize objects to organize react components based on a shared prop (e.g _type). My goal is to automatically determine the correct com ...

Tips for Switching Button Class Triggered by Click Event

I have 2 buttons and I would like to indicate the active button by changing the button class. I attempted to achieve this using removeClass and addClass but encountered an error. Error: removeClass is not a function .component.html <div class="col" ...

Organize JSON data in Angular 6 from an observable based on a specific key

Note: While I am familiar with sorting a regular array of objects using .sort(), I am facing a challenge with an observable object that I am not accustomed to. My task involves retrieving a JSON array of objects with a service: import { Injectable } from ...

Tips for ensuring elements within a modal receive immediate focus when opened in Angular 2

I am relatively new to Angular JS and I am encountering some challenges with implementing a directive in Angular 2 that can manage focusing on the modal when it is opened by clicking a button. There have been similar queries in the past, with solutions pr ...

Leveraging global attributes beyond Vue components - Vue 3

I have created custom service instances in main.ts app.config.globalProperties.$service1 = new Service1(); app.config.globalProperties.$service2 = new Service2(); While I can use these instances inside Vue components, I also want to be able to utilize the ...

There was an unexpected error: The required package "@esbuild/darwin-arm64" could not be located and is essential for esbuild to function properly

After recently upgrading to Angular 17, my application runs smoothly. However, I encountered an error when building the package using ng build: An unhandled exception occurred: The package "@esbuild/darwin-arm64" could not be found, and is needed ...

Encounter a hiccup while installing Angular CLI with NPM

I encountered an issue while trying to install Angular CLI on my local desktop due to a JAVA path error. Despite attempting to install Angular CLI with and without Java, I still face difficulties in the installation process. Error Message: C:\Users& ...

Issue with Typescript and React: Property not found on type 'IntrinsicAttributes'

While working on my app using Meteor, React, and Typescript, I encountered a transpiling error: The property 'gameId' is not recognized in the type 'IntrinsicAttributes & {} & { children?: ReactNode; } In my project, I have a com ...

Preserve the custom hook's return value in the component's state

I am currently facing a challenge in saving a value obtained from a custom hook, which fetches data from the server, into the state of a functional component using useState. This is necessary because I anticipate changes to this value, requiring a rerender ...

Unexpected disconnection from Socket.io server

Utilizing node.js service and angular client with socket.io for extended duration http requests. Service: export const socketArray: SocketIO.Socket[] = []; export let socketMapping: {[socketId: string]: number} = {}; const socketRegister: hapi.Plugin< ...

Creating dynamic class fields when ngOnInit() is called in Angular

I am trying to dynamically create variables in a class to store values and use them in ngModel and other places. I understand that I can assign values to variables in the ngOnInit() function like this: export class Component implements OnInit{ name: st ...

Exploring ways to transform my function into rxjs in Angular

I have successfully implemented a function that is working as intended. Now, I am looking to transform it into an rxjs function with a filter in the rxjs directory. This transformation should involve using both the pipe method and includes method for filte ...

Using optional function arguments with destructured arguments in TypeScript can result in throwing an error

interface Type1 { attr1: string; attr2: string; } interface Type2 { attr1: string; attr2: string; attr3: string; // additional attribute } function fn(config: Type1 | Type2): void { // The error code is displayed above. I am ...

transforming the accordion into a checkbox

https://i.sstatic.net/5y2gv.pngWhile working on my Angular application, I encountered an issue with using the Bootstrap accordion component. I am trying to make the accordion function as a checkbox, where when the checkbox is checked, the accordion expand ...

What is the approach taken by this component to display its child elements?

While delving into the code of react-accessible-accordion, I found myself puzzled by the way it handles rendering its children. The snippet below is from Accordion.tsx: export default class Accordion extends React.Component<AccordionProps> { // ...

Why is the lifecycle callback not being triggered?

I am currently learning how to develop with Vue.js. I have been trying to use the lifecycle callbacks in my code. In my App.vue file, I have implemented the onMounted callback. However, when I run the code, I do not see the message appearing in the consol ...

Creating components with SCSS files in an Angular library can be achieved by following a few simple

After creating an scss app and associating a library, I encountered an issue when trying to create components with .scss files inside the library. Angular automatically assigned a css file to the component created within the library. The application (name ...

Rule in ESLint mandating return type for arrow functions

I currently have the following arrow function within my Angular project: this.httpClient.get('url').subscribe((response)=>{ }); It is important to note that ESLint should detect an error in the above code due to not specifying a return type. ...

In the case of an Angular application, what is the reason behind hotkeys not functioning in Chrome until the user actively engages with the webpage

When using Angular, I have set up various HostListeners to listen for keydown events: @HostListener('window:keydown', ['$event']) keyEvent(evt: KeyboardEvent) { console.log(evt) } I observed in the console logs that these listeners a ...