无法使用未定义的属性缩小简单的 TypeScript 联合类型

Mar*_*oll 5 type-systems typescript typescript2.0 union-types

我有两种联合类型,一种有属性,另一种没有。我认为检查该属性是否存在可以让我缩小范围,但它不起作用。

我创建了这个 Playground repro。另一个非常相似的东西似乎工作得很好。我是否以错误的方式使用工会?

为了完整起见,这是代码:

export interface AuthenticatedProfile {
    readonly userId: string;
    readonly name: string;
}
export interface AnonymousProfile {
    readonly userId: undefined;
    readonly otherProp: string;
}
export type Profile = AnonymousProfile | AuthenticatedProfile;

function handleProfile(prof: Profile) {
    if (prof.userId) {
        console.log(prof.name);
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

tos*_*skv 5

您可以使用类型保护来限制prof参数的类型。

export interface AuthenticatedProfile {
    readonly userId: string;
    readonly name: string;
}
export interface AnonymousProfile {
    readonly userId: undefined;
    readonly otherProp: string;
}
export type Profile = AnonymousProfile | AuthenticatedProfile;

function isAuthenticatedProfile(prof: Profile): prof is AuthenticatedProfile {
    return (<AuthenticatedProfile>prof).name !== undefined;
}

function isAnonymousProfile(prof: Profile): prof is AnonymousProfile {
    return (<AnonymousProfile>prof).otherProp !== undefined;
}

function handleProfile(prof: Profile) {
    if (isAuthenticatedProfile(prof)) {
        console.log(prof.name);
    } else if (isAnonymousProfile(prof)) {
        console.log(prof.otherProp);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在手册的高级类型部分中阅读有关 typescript 中的类型保护的更多信息。