检查变量是否是打字稿联合中的特定接口类型

时间:2015-03-20 17:28:38

标签: typescript typescript1.4

是否可以创建一个typeguard或其他完成相同目的的东西来检查变量是否是打字稿联合中的特定接口类型?

interface Foo { a:string }
interface Bar { b:string }

(function() {
    function doStuff(thing: Foo | Bar) {
        if(typeof thing === 'Foo') {
            console.log('Foo');
        } 
        else if (typeof thing === 'Bar') {
            console.log('Bar');
        }
        else {
            console.log('unknown');
        }
    }

    var thing: Foo = {a:'a'};
    doStuff(thing);
})();

3 个答案:

答案 0 :(得分:6)

从Typescript 1.6开始,您可以使用用户定义的类型保护:

let isFoo = (object: Foo| Bar): object is Foo => {
    return "a" in object;
}

请参阅https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

答案 1 :(得分:5)

typeof没有这样做。它始终返回" string"," number"," boolean"," object"," function",或& #34;未定义"

您可以使用if(thing.a !== undefined) {if(thing.hasOwnProperty('a')) {等测试来测试对象属性。

请注意,您可以创建一个 字符串a和字符串b的对象,因此请注意这种可能性。

答案 2 :(得分:2)

在TypeScript 2中,您可以使用Discriminated Unions,如下所示:

interface Foo {
    kind: "foo";
    a:string;
}
interface Bar {
    kind: "bar";
    b:string;
}
type FooBar = Foo | Bar;
let thing: FooBar;

然后使用if (thing.kind === "foo")测试对象。<​​/ p>

如果您在示例中只有2个字段,我可能会将组合界面作为@ryan-cavanaugh提及,并使两个属性都可选:

interface FooBar {
    a?: string;
    b?: string
}

请注意,在原始示例中,使用if (thing.a !== undefined)测试对象会产生错误Property 'a' does not exist on type 'Foo | Bar'.

使用if (thing.hasOwnProperty('a'))对其进行测试并不会在Foo语句中将类型缩小为if

@ryan-cavanaugh在TypesScript 2.0或2.1中有更好的方法吗?

相关问题