TypeScript-参数属性的类型防护

时间:2019-06-04 10:31:57

标签: typescript

假设我有一个功能,例如

export function is<T extends string>(
  element: ModdleElement,
  type: T
): element is BpmnElement<T>;

让我们添加一个超载

export function is<T extends string>(
  element: Base,
  type: T
): boolean;

Base界面是

interface Base {
   businessObject: ModdleElement;
}

我想将类型保护也用于重载,应用于businessObject字段,以便

if (is(base, '...')) {
   const t = base.businessObject.myProp; // Correctly cast
}

这可能吗?

1 个答案:

答案 0 :(得分:2)

类型防护通常通过缩小联合来起作用。在这种情况下,Base不是联合,但是我们仍然可以使用与is返回类型中具有指定子类型的属性的对象的交集来使事情正常进行。

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
}