To achieve your desired outcome, you can utilize a union type like this:
type Family = {
members: Member[],
memberIds: string[]
} | {
members: undefined
}
With this setup, a Family
can either consist of a list of members
and corresponding memberIds
, or the members
property can simply be undefined, in which case there may or may not be a list of memberIds
. By checking the members
property, you can effectively narrow down the type:
function validate(f: Family): void {
if(f.members) {
// f: { members: Member[], memberIds: string[] } - all good
console.log(f.memberIds);
} else {
// f: { members: undefined } - type error
console.log(f.memberIds);
}
}
One limitation to this approach is that the members
property must be present, even when set to undefined. You'll need to explicitly define it as { members: undefined }
rather than simply {}
, as that's required for it to conform to the Family
type.
Trying to declare the type with members?: undefined
as an optional property won't work, as it disrupts the union structure and leads to the type getting needlessly narrowed to f: never
in the function.