Reputation: 21114
Let's say I have a function such as
export function is<T extends string>(
element: ModdleElement,
type: T
): element is BpmnElement<T>;
Let's add an overload
export function is<T extends string>(
element: Base,
type: T
): boolean;
The Base
interface is
interface Base {
businessObject: ModdleElement;
}
I'd like to apply the type guard also for the overload, to the businessObject
field, so that
if (is(base, '...')) {
const t = base.businessObject.myProp; // Correctly cast
}
Is this possible?
Upvotes: 0
Views: 432
Reputation: 249506
Type guards usually work by narrowing unions. In this case Base
is not a union, but we ca still get things to work using an intersection with something that has a property of the specified sub-type in the is
return type .
class ModdleElement { p: any; } // placeholder
class BpmnElement<T> extends ModdleElement { myProp: T } // placeholder
export declare function is<T extends string>(
element: ModdleElement,
type: T
): element is BpmnElement<T>;
export declare function is<T extends string>(
element: Base,
type: T
): element is (Base & { businessObject: BpmnElement<T> });
interface Base {
businessObject: ModdleElement;
}
declare let base: Base;
if (is(base, '...')) {
const t = base.businessObject.myProp; // Correctly cast
}
Upvotes: 2