How can I effectively narrow types based on the value of a single field in TypeScript? It seems that using type predicates may not be working as expected to narrow down the types of other parameters within a type. Is there a way to ensure correct type narrowing in this scenario?
export function isTrue(input: boolean | undefined | null): input is true {
return input === true;
}
type Refine =
| {
b: true;
c: 'bIsTrue';
}
| {
b: undefined;
c: 'bIsUndefined';
}
| {
b: false;
c: 'bIsFalse';
};
export function example() {
const example = (null as unknown) as Refine;
if (example.b === true) {
example.b; // Type is now: true
example.c; // Type is now: 'bIsTrue'
}
if (isTrue(example.b)) {
example.b; // Type is now: true
example.c; // Type is now: 'bIsTrue' | 'bIsUndefined' | 'bIsFalse'
}
}