Typescript 如何检查接口类型的联合参数

Typescript 如何检查接口类型的联合参数,typescript,Typescript,在上面的代码中,您可以猜到IGovedo和IKrava是接口类型。 如果我使用这种方法,检查args是IGovedo、IKrava、null还是未定义的最好方法是什么 使用了typescript的最新版本1.6 已编辑:不是旧问题的真正副本,而是已解决-标记的解决答案。您需要的是用户定义的类型保护功能 callbackFn(args: IGovedo | IKrava) { // How to check here type of args } 不可能在运行时检查接口instanceO

在上面的代码中,您可以猜到IGovedo和IKrava是接口类型。 如果我使用这种方法,检查args是IGovedo、IKrava、null还是未定义的最好方法是什么

使用了typescript的最新版本1.6


已编辑:不是旧问题的真正副本,而是已解决-标记的解决答案。

您需要的是用户定义的类型保护功能

callbackFn(args: IGovedo | IKrava) {
   // How to check here type of args 
}

不可能在运行时检查接口
instanceOf
仅适用于类文档链接的可能副本,以供参考:
interface IGovedo {
    govedo: string;
}

interface IKrava {
    krava: string;
}

function isGovedo(object: any): object is IGovedo {
    return 'govedo' in object;
}

let foo: IGovedo | IKrava;

if (isGovedo(foo)) {
    // foo has type IGovedo;
} else {
    // foo has type IKrava.
}