[英]Destructuring of union types in typescript
是否有一种方法(类似于函数式语言的模式匹配)来解构TypeScript中的联合类型,即一些构造如:
var a: Foo | Bar = ...;
a match {
case f: Foo => //it's a Foo!
case b: Bar => //it's a Bar!
}
如果没有这样的结构 - 在创建这样的结构时是否有任何技术困难?
TypeScript将Type Guard视为分解联合类型的一种方式。 有几种方法可以使用它。
如果Foo
或Bar
是一个类,您可以使用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'
来测试union中的基本类型( string
, number
或boolean
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.