是否有一种方法(类似于函数式语言的模式匹配)来解构TypeScript中的联合类型,即一些构造如:
var a: Foo | Bar = ...;
a match {
case f: Foo => //it's a Foo!
case b: Bar => //it's a Bar!
}
Run Code Online (Sandbox Code Playgroud)
如果没有这样的结构 - 在创建这样的结构时是否有任何技术困难?
TypeScript将Type Guard视为分解联合类型的一种方式.有几种方法可以使用它.
如果Foo或是Bar一个类,您可以使用instanceof:
if (a instanceof Foo) { a.doFooThing(); }
Run Code Online (Sandbox Code Playgroud)
如果它们是接口,您可以编写用户定义的类型保护:
function isFoo(f: any): f is Foo {
// return true or false, depending....
}
if (isFoo(a)) {
a.doFooThing();
} else {
a.doBarThing();
}
Run Code Online (Sandbox Code Playgroud)
你也可以用typeof a === 'string'在联合测试基本类型(string,number或boolean)
| 归档时间: |
|
| 查看次数: |
701 次 |
| 最近记录: |