【问题标题】:Refining typescript disjoint union精炼打字稿不相交并集
【发布时间】: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 分支中。

有什么办法让它明白这一点吗?

【问题讨论】:

标签: typescript disjoint-union


【解决方案1】:

你不能访问工会的成员,除非他们是共同的。您可以改用 in 类型保护:

type Base = { s: string };
type Extra = { foo: string; };
type Other = { bar: string; };
type T = Base & (Extra | Other);

function f(o: T): string {
    if ('foo' in o) {
        return o.s + o.foo;
    }
    return o.s + o.bar;
}

【讨论】:

    猜你喜欢
    • 2020-03-16
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 2022-01-13
    • 2019-04-13
    • 1970-01-01
    相关资源
    最近更新 更多