The type of the object to be checked.
The type representing the path to the discriminant property in the object.
The type of the value to match against the discriminant property.
The object to be checked.
A string representing the path to the nested discriminant property. The path is dot-separated (e.g., 'prop1.type').
The value to compare against the value of the discriminant property. If the value at the nested path equals this value, the function returns true, otherwise false.
true
if the value at the specified path in the object
matches the discriminatorValue
, otherwise false
.
If the function returns true
, the type of obj
is narrowed down
in the context where this function is used.Note: This function assumes that the path provided in discriminator
is valid for the object's type.
If the path is invalid, TypeScript will not be able to infer the correct type.
type Prop1 = { type: "a"; prop1: "a" } | { type: "c"; prop1: "a" };
interface TestData {
type: "a";
prop1:
| {
type: "a";
prop2: number;
prop1: Prop1;
}
| {
type: "b";
prop3: string;
prop1: Prop1;
};
prop2: {
prop4: boolean;
};
}
const examp: TestData = {
type: "a",
prop1: {
type: "a",
prop2: 0,
prop1: {
type: "a",
prop1: "a",
},
},
prop2: {
prop4: false,
},
};
it("should narrow down nested discriminated unions", () => {
type Expected = {
type: "a";
prop1: {
type: "a";
prop2: number;
prop1: Prop1;
};
prop2: {
prop4: boolean;
};
};
const res = (() => {
if (nestedGuard(examp, "prop1.type", "a")) {
return examp
}
return;
})();
if (res === undefined) {
return;
}
expectTypeOf(res).toEqualTypeOf<Expected>();
expect(res).toBeDefined()
console.log(res.prop1.prop2); // Nested type information is retained
});
Generated using TypeDoc
A type guard function that discriminates nested properties within a complex type structure. It checks if the specified nested property (discriminator) of an object matches a given value. This function is particularly useful for discriminating union types based on nested discriminators.
Provides auto path inference to nested string union fields and autocomplete on the available values on the discriminant field.