interface A = {
name: string;
...
};
interface B = {
name: string;
...
};
interface C = {
key: string;
...
};
type UnionOfTypes = A | B | C | ...;
function hasName(item: UnionOfTypes) {
if ("name" in item) {
item; // typescript knows here that item is either A or B
}
}
Can I automatically infer types like if("name" in item)
does? My code only uses interfaces/types and not classes.
This way I wouldn't have to explicitly define
function hasName(item: UnionOfTypes): item is A | B {
...
}
I'm thinking of using other type guards later on, or are there reasons why narrowing down types this way should be avoided?