I have a parent component that has to pass an object in @Input to the child component, but the object may not always be the same. For example, can i have:
@Input() obj: string | number;
?
In my specific case i have two different objects as possibles inputs:
@Input() obj: AppDetail | AbsDetail;
Is it possible to do so?
CodePudding user response:
Judging by your comment you have issues reaching fields that do not overlap in the types. There are three ways around this:
use an
@Input
for every different type. But that's not your question :)use
&
instead of|
for your@Input
type:
@Input() obj: AppDetail & AbsDetail;
It's the quickest, but not the type safest solution, so use with caution. This will do an intersect of your type objects
- You assert first what type it is before continuing in your code. For example:
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)) {
// here you can access obj.id without a typescript error
} else {
// here you can access obj.code without a typescript error
// because it's not AppDetail, the compiler knows that it should be AbsDetail
}
}
}