打字稿中联合类型的解构

时间:2015-11-20 17:18:15

标签: typescript

是否有一种方法(类似于函数式语言的模式匹配)来解构TypeScript中的联合类型,即一些构造如:

var a: Foo | Bar = ...;

a match {
   case f: Foo => //it's a Foo!
   case b: Bar => //it's a Bar!
}

如果没有这样的构造 - 在创建这样的构造时是否有任何技术困难?

1 个答案:

答案 0 :(得分:5)

TypeScript将Type Guards理解为分解联合类型的一种方式。有几种方法可以使用它。

如果FooBar是一个班级,您可以使用instanceof

if (a instanceof Foo) { a.doFooThing(); }

如果他们是接口,您可以编写用户定义的类型保护:

function isFoo(f: any): f is Foo {
    // return true or false, depending....
}
if (isFoo(a)) {
   a.doFooThing();
} else {
   a.doBarThing();
}

您还可以使用typeof a === 'string'来测试联合中的基本类型(stringnumberboolean

相关问题