【发布时间】:2019-02-27 22:56:44
【问题描述】:
我正在尝试使以下内容正常工作,但是 typescript 在尝试访问 o.foo 属性时输出错误:
type Base = { s: string };
type Extra = { foo: string; };
type Other = { bar: string; };
type T = Base & (Extra | Other);
function f(o: T): string {
if (typeof o.foo === 'string') {
return o.s + o.foo;
}
return o.s + o.bar;
}
错误是
Property 'foo' does not exist on type 'T'.
Property 'foo' does not exist on type 'Base & Other'.
似乎打字稿无法正确推断出如果o 具有foo 属性,即字符串,那么o 的类型必须在联合的Base & Extra 分支中。
有什么办法让它明白这一点吗?
【问题讨论】:
-
这在 flow 中是可能的(参见 flow.org/en/docs/types/unions/#toc-unions-refinements 中的“Disjoint Unions”),但我不确定它在 typescript 中是否有效。