首页 > 解决方案 > 精炼打字稿不相交的联合

问题描述

我正在尝试使以下内容起作用,但是打字稿在尝试访问该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属性,即字符串,那么 of 的类型o必须在Base & Extra联合的分支中。

有没有办法让它明白这一点?

标签: typescriptdisjoint-union

解决方案


除非他们很常见,否则您无法访问工会成员。您可以改用intypeguard:

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;
}

推荐阅读