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:
Consider using an @Input
for each distinct type. However, I understand that this may not directly answer your question :)
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
- 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.
}
}
}