无法使用未定义的属性缩小简单的TypeScript联合类型 [英] Can't narrow simple TypeScript union type with undefined property

查看:129
本文介绍了无法使用未定义的属性缩小简单的TypeScript联合类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two unioned types, one has a property and the other one hasn't. I assumed that checking for the existence of that property would allow me to narrow it down, but it isn't working.

我创建了

I've created this Playground repro. This other very similar thing seems to work just fine. Am I using unions the wrong way?

为完整起见,以下是代码:

Here's the code for the sake of completeness:

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

谢谢!

推荐答案

您可以使用类型防护来限制 prof 参数的类型.

You can use type guards to restrict the type of the prof parameter.

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

您可以在手册.

这篇关于无法使用未定义的属性缩小简单的TypeScript联合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆